I have a few model classes that extend LinkedHashMap<String, Object>: they define getters and setters which wrap the Map's get and put methods. I am trying to serialize instances of these classes using Jackson (with RESTEasy), but Jackson refuses to pay attention to my getters, which are annotated with #JsonProperty. Instead, it is only serializing the key-value pairs of the backing map. I tried using #JsonAutoDetect to disable auto-detection for all methods and fields, but that didn't change anything. Is there a way to prevent Jackson from automatically serializing a Map, or must I create new model classes that don't extend LinkedHashMap<String, Object>?
I agree with #skaffman's response. But if you could not easily change inheritance structure drastically, there may be ways around this.
One possibility is that if you do have an interface that defines getters/setters, you could add
#JsonSerialize(as=MyInterface.class)
#JsonDeserialize(as=MyInterface.class)
which would force Jackson to only use whatever is available via specific interface.
Custom serializers/deserializers are also a possibility, but that's quite a bit of work.
I have a few model classes that extend LinkedHashMap<String, Object>: they define getters and setters which wrap the Map's get and put methods
This is a classic example of when not to use inheritance: you're finding that some other piece of code (i.e. Jackson) is treating your class like an instance of its superclass, which isn't what you want it to do. In cases like these (and also in general), it's usually better to use composition rather than inheritance.
I recommend rewriting your model class to contain a map, rather than extending one. You get much more control than way, and the resulting model is less brittle. If you need to view your model as a Map, then implement an asMap method (or something similar) which renders that view.
You can implement your own org.codehaus.jackson.map.DeserializerProvider which extends Jackson's org.codehaus.jackson.map.deser.StdDeserializerProvider and overwrite method _createDeserializer:
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.deser.StdDeserializerProvider;
import org.codehaus.jackson.map.DeserializationConfig;
...
class MyDeserializerProvider extends StdDeserializerProvider {
#Override
protected JsonDeserializer<Object> _createDeserializer(DeserializationConfig config, JavaType type, BeanProperty property) throws JsonMappingException {
if (type.isMapLikeType()) { // (1)
return this._factory.createBeanDeserializer(config, this, type, property);
} else {
return super._createDeserializer(config, type, property);
}
}
}
(1) use if-condition that meets your needs
The custom deserializer is registered directly at the ObjectMapper:
ObjectMapper om = new ObjectMapper();
om.setDeserializerProvider(new MyDeserializerProvider());
I tested this with Jackson 1.9.11.
In newer versions of jackson (>= 2.9, I guess) simply annotate your class with
#JsonFormat(shape = JsonFormat.Shape.OBJECT)
Related
The AS3 Proxy class extends Object and exposes methods that you can override to handle the addition/removal and getting/setting of properties on the object in a universal fashion.
It appears that existing objects such as MovieClip, Sprite, etc. do not inherit from the Proxy class, so it would seem to preclude the possibility of adding such functionality to existing display object classes.
I've created a layout framework with a base display object class called GUIControl that inherits from MovieClip, and I was hoping to add data-binding functionality to it by overriding the Proxy class's setProperty method, so I could handle property assignments with a single handler to make all properties function as binding sources by default.
Is there some way to utilize the Proxy class's functionality on existing classes, or am I stuck building classes from scratch based on Proxy?
You may create a wrapper class for MovieClip and set property on the wrapper. You should override other functions in Proxy and call the relative functions on MovieClip.
Here is an example
import flash.display.MovieClip;
import flash.utils.Proxy;
import flash.utils.flash_proxy;
public class MovieClipWrapper extends Proxy
{
public function MovieClipWrapper(target:MovieClip)
{
super();
_target = target;
}
private var _target:MovieClip;
override flash_proxy function setProperty(name:*, value:*):void
{
//set data on target movieClip, or call the notify functions
}
}
No, it cannot be used on existing classes. The worst part is that rules out using Proxy on any display list classes. There is no way to alter a property on a display list class and have the Proxy class intercept and handle the setting or getting of such a property value. Proxy is useful only as a base class for new classes (ideally dynamic classes), where you want to intercept and run logic when properties are set/retreived/removed.
Futhermore, Proxy is useless for trying to wrap something like the Dictionary class, since Proxy's interface methods rely on QName and String-type keys exclusively, which makes it impossible to enumerate over, get, or set Dictionary values that use object instances as keys... something Dictionary supports unlike associative arrays or normal Objects.
i'm using the Restlet library for a WS server and i've recently switched from XStream/Jettison to Jackson as a JSON serializer/deserializer because of some issues.
A first drawback is that my ArrayList< Profile > (previously a Vector with Jettison) it doesn't wrap the list of Profiles when serialized and the JSON instead of "Profile:[{firstProfile}, {secondProfile}]" it looks like: [{firstProfile}, {secondProfile}]
I can overcome to this issue in the client telling manually which is the correct mapping but i would prefer to use a KVC approach.
I've looked around and it seems that it's a known issue: http://wiki.fasterxml.com/JacksonPolymorphicDeserialization (5.1 Missing type information on Serialization) that it suggest to:
Use arrays instead of Lists
Sub-class list, using class MyPojoList extends ArrayList { }
Force use of specific root type
the simplest way it should be to return an "Profile[] profile" array but it seems not working, before trying the other solutions i've rechecked around and it seems that you can use a #XmlRootElement(name = "Profile") to wrap the JSON root element: http://jira.codehaus.org/browse/JACKSON-163?focusedCommentId=213588&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-213588
so for using JAXB annotations with Jackson you need to configure the objectMapper: http://wiki.fasterxml.com/JacksonJAXBAnnotations
but in restlet to do so you need to override createObjectMapper to pass a Custom converter (see: http://restlet-discuss.1400322.n2.nabble.com/Set-custom-objectMapper-to-Jackson-Extension-td6287812.html and http://restlet-discuss.1400322.n2.nabble.com/Jackson-Mix-in-Annotations-td6211060.html#a6231831)
this is what i'm trying now! the question is there a more straightforward way to achieve this??
Thanks!!
the solution for me is to annotate the Profile class with:
#JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.WRAPPER_OBJECT)
public class Profile extends Element implements Serializable {
and now the json now looks like:
{"Profile":{ ... }}
and the return type is a Sub-classed list:
public class ProfileList extends ArrayList<Profile>
{}
see http://wiki.fasterxml.com/JacksonPolymorphicDeserialization 5.1
I think what you want is not really available in a sense that JAX-B seems to have some rules on how to deal with lists. See this converstation on the RESTeasy mailing list
I'm using Spring MVC to handle JSON POST requests. Underneath the covers I'm using the MappingJacksonHttpMessageConverter built on the Jackson JSON processor and enabled when you use the mvc:annotation-driven.
One of my services receives a list of actions:
#RequestMapping(value="/executeActions", method=RequestMethod.POST)
public #ResponseBody String executeActions(#RequestBody List<ActionImpl> actions) {
logger.info("executeActions");
return "ACK";
}
I have found that Jackson maps the requestBody to a List of java.util.LinkedHashMap items (simple data binding). Instead, I would like the request to be bound to a List of typed objects (in this case "ActionImpl").
I know this is easy to do if you use Jackson's ObjectMapper directly:
List<ActionImpl> result = mapper.readValue(src, new TypeReference<List<ActionImpl>>() { });
but I was wondering what's the best way to achieve this when using Spring MVC and MappingJacksonHttpMessageConverter. Any hints?
Thanks
I have found that you can also work around the type erasure issue by using an array as the #RequestBody instead of a collection. For example, the following would work:
public #ResponseBody String executeActions(#RequestBody ActionImpl[] actions) { //... }
I suspect problem is due to type erasure, i.e. instead of passing generic parameter type, maybe only actions.getClass() is passed; and this would give type equivalent of List< ?>.
If this is true, one possibility would be to use an intermediate sub-class, like:
public class ActionImplList extends ArrayList<ActionImpl> { }
because this will the retain type information even if only class is passed.
So then:
public #ResponseBody String executeActions(#RequestBody ActionImplList actions)
would do the trick. Not optimal but should work.
I hope someone with more Spring MVC knowledge can shed light on why parameter type is not being passed (perhaps it's a bug?), but at least there is a work around.
For your information, the feature will be available in Spring 3.2 (see https://jira.springsource.org/browse/SPR-9570)
I just tested it on current M2 and it works like a charm out of the box (no need to provide additionnal annotation to provide the parameterized type, it will be automatically resolved by new MessageConverter)
This question is already old, but I think I can contribute a bit anyway.
Like StaxMan pointed out, this is due to type erasure. It definitely should be possible, because you can get the generic arguments via reflection from the method definition. However, the problem is the API of the HttpMessageConverter:
T read(Class<? extends T> clazz, HttpInputMessage inputMessage);
Here, only List.class will be passed to the method. So, as you can see, it is impossible to implement a HttpMessageConverter that calculates the real type by looking at the method parameter type, as that is not available.
Nevertheless, it is possible to code your own workaround - you just won't be using HttpMessageConverter. Spring MVC allows you to write your own WebArgumentResolver that kicks in before the standard resolution methods. You can for example use your own custom annotation (#JsonRequestBody?) that directly uses an ObjectMapper to parse your value. You will be able to provide the parameter type from the method:
final Type parameterType= method.getParameterTypes()[index];
List<ActionImpl> result = mapper.readValue(src, new TypeReference<Object>>() {
#Override
public Type getType() {
return parameterType;
}
});
Not really the way TypeReference was intended to be used I presume, but ObjectMapper doesn't provide a more suitable method.
Have you tried declaring the method as:
executeActions(#RequestBody TypeReference<List<ActionImpl>> actions)
I haven't tried it, but based on your question it's the first thing I would try.
Please retag this question to include languages to which it is relevant
So my java book had a whole chapter on nested classes, but ended on the note that you should only really use them when it comes to "modeling composition relationships and implementing internals of a class you want to hide". So lets discuss when you would want to use nested classes and some examples.
A nested/inner class is just a class that's only ever used specifically in the context of another class, which doesn't have it's own class file. If it's linked to an instance, it can only be instantiated in the context of a parent class instance; it can see private data, or only private static data if it's a static class.
The java developer site has a nested classes tutorial with one example:
http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html
A couple examples of usage:
Hide a concrete implementation of an
interface:
(Thinking of a database session for a tool like Hibernate): Suppose you have a Session interface, and a SessionFactory which returns an instance of a Session. The SessionImpl concrete class that implements the Session interface could be an innner class of the factory that knows how to construct and initialize it.
Supply information by implementing an
interface:
In the Wicket web framework, each GUI component has an associated "model", whose job is to wire data to the component. The interface looks something like:
public interface IModel extends IDetachable {
public Object getObject();
public Object setObject();
}
Suppose you have some special logic to retrieve data for a custom GUI component that you've written. Since no other component retrieves data the same way, you could use an anonymous class at the point where the IModel is supplied to take care of the data retrieval. If you have another point in the same class where you need to reuse your IModel implementation, you could make it an inner class. Later, if you need the model elsewhere, you could convert it to a top-level class.
Generally you use an inner class in a situation where you need a class definition, but that class is only usable or only makes sense in the context of the parent class.
A real life usage i had with nested classes, was in a global settings object.
The parent class was a Singleton, with nested classes as settings categories.
Settings
File settings
Print settings
Etc.
There was no real point in making the inner object as separate classes, as their would be no use for them outside the settings class scope.
I use nested classes for encapsulating algorithms that would be usually done as a method with lots of arguments. I use class that has raw data and I put algorithms into separate file in nested class (using partial keyword). That way I can put properties for that algorithm and its (working) data lives after algorithm is done.
I know that can be easily done without nested classes but this feels right because algorithm is purposely built for parent class.
public partial class Network
{
partial void initFDLF()
{
fdlf=new FDLF(this);
}
public FDLF fdlf;
public class FDLF
{
internal bool changed=true;
internal bool pvchange=true;
public double epsilon = 0.001;
public bool fdlfOk=false;
public void init(){...}
public void run(){...}
...
Method chaining is the only way I know to build fluent interfaces.
Here's an example in C#:
John john = new JohnBuilder()
.AddSmartCode("c#")
.WithfluentInterface("Please")
.ButHow("Dunno");
Assert.IsNotNull(john);
[Test]
public void Should_Assign_Due_Date_With_7DayTermsVia_Invoice_Builder()
{
DateTime now = DateTime.Now;
IInvoice invoice = new InvoiceBuilder()
.IssuedOn(now)
.WithInvoiceNumber(40)
.WithPaymentTerms(PaymentTerms.SevenDays)
.Generate();
Assert.IsTrue(invoice.DateDue == now.AddDays(7));
}
So how do others create fluent interfaces. How do you create it? What language/platform/technology is needed?
The core idea behind building a fluent interface is one of readability - someone reading the code should be able to understand what is being achieved without having to dig into the implementation to clarify details.
In modern OO languages such as C#, VB.NET and Java, method chaining is one way that this is achieved, but it's not the only technique - two others are factory classes and named parameters.
Note also that these techniques are not mutually exclusive - the goal is to maximize readabilty of the code, not purity of approach.
Method Chaining
The key insight behind method chaining is to never have a method that returns void, but to always return some object, or more often, some interface, that allows for further calls to be made.
You don't need to necessarily return the same object on which the method was called - that is, you don't always need to "return this;".
One useful design technique is to create an inner class - I always suffix these with "Expression" - that exposes the fluent API, allowing for configuration of another class.
This has two advantages - it keeps the fluent API in one place, isolated from the main functionality of the class, and (because it's an inner class) it can tinker with the innards of the main class in ways that other classes cannot.
You may want to use a series of interfaces, to control which methods are available to the developer at a given point in time.
Factory Classes
Sometimes you want to build up a series of related objects - examples include the NHibernate Criteria API, Rhino.Mocks expectation constraints and NUnit 2.4's new syntax.
In both of these cases, you have the actual objects you are storing, but to make them easier to create there are factory classes providing static methods to manufacture the instances you require.
For example, in NUnit 2.4 you can write:
Assert.That( result, Is.EqualTo(4));
The "Is" class is a static class full of factory methods that create constraints for evaluation by NUnit.
In fact, to allow for rounding errors and other imprecision of floating point numbers, you can specify a precision for the test:
Assert.That( result, Is.EqualTo(4.0).Within(0.01));
(Advance apologies - my syntax may be off.)
Named Parameters
In languages that support them (including Smalltalk, and C# 4.0) named parameters provide a way to include additional "syntax" in a method call, improving readability.
Consider a hypothetical Save() method that takes a file name, and permissions to apply to the file after saving:
myDocument.Save("sampleFile.txt", FilePermissions.ReadOnly);
with named parameters, this method could look like this:
myDocument.Save(file:"SampleFile.txt", permissions:FilePermissions.ReadOnly);
or, more fluently:
myDocument.Save(toFile:"SampleFile.txt", withPermissions:FilePermissions.ReadOnly);
You can create a fluent interface in any version of .NET or any other language that is Object Oriented. All you need to do is create an object whose methods always return the object itself.
For example in C#:
public class JohnBuilder
{
public JohnBuilder AddSmartCode(string s)
{
// do something
return this;
}
public JohnBuilder WithfluentInterface(string s)
{
// do something
return this;
}
public JohnBuilder ButHow(string s)
{
// do something
return this;
}
}
Usage:
John = new JohnBuilder()
.AddSmartCode("c#")
.WithfluentInterface("Please")
.ButHow("Dunno");
AFAIK, the term fluent interface does not specify a specific technology or framework, but rather a design pattern. Wikipedia does have an extensive example of fluent interfaces in C♯.
In a simple setter method, you do not return void but this. That way, you can chain all of the statements on that object which behave like that. Here is a quick example based on your original question:
public class JohnBuilder
{
private IList<string> languages = new List<string>();
private IList<string> fluentInterfaces = new List<string>();
private string butHow = string.Empty;
public JohnBuilder AddSmartCode(string language)
{
this.languages.Add(language);
return this;
}
public JohnBuilder WithFluentInterface(string fluentInterface)
{
this.fluentInterfaces.Add(fluentInterface);
return this;
}
public JohnBuilder ButHow(string butHow)
{
this.butHow = butHow;
return this;
}
}
public static class MyProgram
{
public static void Main(string[] args)
{
JohnBuilder johnBuilder = new JohnBuilder().AddSmartCode("c#").WithFluentInterface("Please").ButHow("Dunno");
}
}
Sometime ago I had the same doubts you are having now. I've done some research and now I'm writing a series of blog posts about techinics of designing a fluent interface.
Check it out at:
Guidelines to Fluent Interface design in C# part 1
I have a section there about Chaining X Nesting that can be interesting to you.
In the following posts I will talk about it in a deeper way.
Best regards,
André Vianna
Fluent interface is achieved in object oriented programming by always returning from your methods the same interface that contains the method. Consequently you can achieve this effect in java, javascript and your other favorite object oriented languages, regardless of version.
I have found this technique easiest to accomplish through the use of interfaces:
public interface IFoo
{
IFoo SetBar(string s);
IFoo DoStuff();
IFoo SetColor(Color c);
}
In this way, any concrete class that implements the interface, gets the fluent method chaining capabilities. FWIW.. I wrote the above code in C# 1.1
You will find this technique littered throughout the jQuery API
A couple of things come to mind that are possible in .Net 3.5/C# 3.0:
If an object doesn't implement a fluent interface, you could use Extension Methods to chain your calls.
You might be able to use the object initialization to simulate fluent, but this only works at instantiation time and would only work for single argument methods (where the property is only a setter). This seems hackish to me, but the there it is.
Personally, I don't see anything wrong with using function chaining if you are implementing a builder object. If the builder object has chaining methods, it keeps the object you are creating clean. Just a thought.
This is how I've built my so called fluent interfaces or my only forary into it
Tokenizer<Bid> tkn = new Tokenizer<Bid>();
tkn.Add(Token.LambdaToken<Bid>("<YourFullName>", b => Util.CurrentUser.FullName))
.Add(Token.LambdaToken<Bid>("<WalkthroughDate>",
b => b.WalkThroughDate.ToShortDateString()))
.Add(Token.LambdaToken<Bid>("<ContactFullName>", b => b.Contact.FullName))
.Cache("Bid")
.SetPattern(#"<\w+>");
My example required .net 3.5 but that's only cause of my lambda's. As Brad pointed out you can do this in any version of .net. Although I think lambda's make for more interesting possibilities such as this.
======
Some other good examples are nHibernate's Criteria API, there is also a fluent nhibernate extension for configuring nhibernate but I've never used it
Dynamic keyword in C# 4.0 will make it possible to write dynamic style builders. Take a look at following article about JSON object construction.