Serializing objects with flexjson - java

I am trying to use flexjson library. But in my object I have to use:
com.google.api.client.util.DateTime which do not have no parameters constructor. I always get NoSuchMethodException with message: Flexjson will instantiate any protected, private, or public no-arg constructor. I have sources and trying to do something with that, here is the code:
constructor = clazz.getDeclaredConstructor();
constructor.setAccessible(true);
return constructor.newInstance();
Exception is being thrown in clazz.getDeclaredConstructor() due to lacking empty constructor. What is the best approach to find constructor with let's say those signature:
DateTime(long timestamp)?
Have anyone encounter this kind of problem with this library? Maybe you can suggest to use other one. I am using it to serialize objects generated by Google Cloud Endpoints. Maybe I can do that with different approach?

You don't have to change the source code of Flexjson to do this. The way to handle this is to create your own implementation of ObjectFactory and register that for the type you are binding into. From there you can instantiate it however, you desire. It's easiest to subclass BeanObjectFactory and override the method instantiate(). In there you can do whatever you want to create an instance of an object you wish. By subclassing BeanObjectFactory it will take care of binding the individual properties from the JSON into your object using the setter/getter of that object. If your object doesn't support property methods you might find it easier to implement ObjectFactory and manually setting the values on that object from the JSON. There is lots of documentation on the Flexjson website about building ObjectFactories.
Then you can register your ObjectFactory to that data type using:
new JSONDeserializer<SomeObject>()
.use( DateTime.class, new DateTimeObjectFactory() )
.deserialize(json);

Related

Ajax call with Jackson marshaling of subclasses (Spring MVC)

I have a controller that receives an abstract class.
This class has 3 different subclasses.
In order for the controller to receive the ajax call i must add a "#class" : com.my.project.my.Class
parameter to the object i'm sending.
This feels really bad to implement.
Is there any other ways to send the subclasses and avoiding forcing the client to pass an actual class name with each call.
Thanks
Jackson has its own inheritance handling mechanism. You don't necessarily need to use #class. See here.
This feature cannot be the cleanest. Jackson does its deserialization through hints from the developer. Notice how you always pass a Class or TypeReference object when interacting with its ObjectMapper. In the same way, the JSON needs to contain hints for which subtype to deserialize to.

Customizing Field Name Serialization in Jackson Object Mapper

Say I have a bean:
public class MyBean {
public String oneMississipi;
public int myBestFriend;
//Getters&Setters&Bears,Oh my.
}
And I am using com.fasterxml.Jackson DataBinding to transform instances of this pojo into json output... How do I customize the serialization of field names and can this be scoped to a global/class/field level?
e.g. I wish to dasherize my field names:
{
"one-mississipi": "two mississippi",
"my-best-friend": 42
}
I have already spent hours in Google and even trawling through the jackson code in order to find out where the field serialization occurs, but can't seem to see anywhere that it may delegate for custom field processing.
Does anyone have any ideas as to where this functionality lies if any? Much appreciated
Implement PropertyNamingStrategy and inside the resolving methods use AnnotatedMethod, AnnotatedField or AnnotatedParameter to get the declaring class. Then you can look for any custom annotation on that class and apply any custom naming depending on it.
The biggest problem with this approach is that it's not possible to get the actual concrete class being serialized or deserialized, it will always return the declaring class. So it won't be possible to override naming behavior in subtypes for the inherited members unless you bring them into the subtype.
Another solution would be using different mappers for classes that have different naming strategies. You can make it more or less transparent by creating a top-level "router" mapper that will decide which mapper instance to use (special care must be taken for configuration methods and other non ser/deser related methods). Assuming that you will have a finite number of the strategies this solution should be workable too.
The drawback of this solution is that you won't be able to mix different naming strategies during a single serialization / deserialization run.

Type Information within serialized JSON using GSON

Using Jackson we have the option to attach the type info to the serialized object (http://jackson.codehaus.org/1.5.5/javadoc/org/codehaus/jackson/annotate/JsonTypeInfo.html).
Is there a way to do this using GSON like:
{
propertyName:"test",
_className:"foo.bar.TestClass"
}
The idea is to have it generic, so when a ArrayList<Object> is deserialized, the right object instances are restored with it.
I saw this question: https://stackoverflow.com/a/8683689/1001027 that is more or less what I need but it works just for a specific class of objects. How could implement is in such a generic way, that every object would be serialized with this property?
You need to implement deserializer, which will look at the type property and cast objects to a given type. I believe, there is no other way.
Check out the javadoc, implementing this interface may be your answer.

XStream deserialize object through desired constructor

In xstream for java, is there a way to deserialize an object by ensuring that it goes thru a specific constructor with parameters?
XStream (or deserialization in general) doesn't call constructors. (Except in the rarely used Pure Java Mode, when it calls the default constructor.)
You need to use the readResolve() method if you want to initialise transient fields.
However you can write your own converter, and then you can do whatever you want. This approach works best if you have one specific class that you want to apply this to.

How to unwrap the original object from a dynamic proxy

what's the best approach to unwrap a dynamic proxy to retrieve the original object beneath?
The dynamic proxy has been created using java.lang.reflect.Proxy.newProxyInstance()
Thank you.
There's no good method: Proxy.getInvocationHandler(proxy) returns handler, but the problem is to extract the original object from the handler. If your handler is an anonymous class, the only way to extract original object is to use reflection and extract original from field named val$something - very ugly method.
Better way is to create non-anonymous handler class with a getter, then you do:
((YourHandler)Proxy.getInvocationHandler(proxy)).getOriginalObject()
Each proxy has an InvocationHandler associated with it. Only the InvocationHandler knows which object (if any) underlies the proxy. If you control the creation of the proxy, then you can supply your own InvocationHandler that will have the extra functionality that you desire (i.e. will be able to disclose the underlying object.) If you don't, then I am afraid you're out of luck.
You can use the Proxy.getInvocationHandler(proxy) method to obtain the original InvocationHandler.

Categories