Question

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?

Was it helpful?

Solution

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top