How to force FlexJson in java to deserialize a json object to a string?
Question
So I'm getting an object back from a server that looks like this:
{
"Status": {
"stuff":"stuff...";
"morestuff":"morestuff...";
};
"Data": { ... another object ... };
}
However, when I get this object back, I want to deserialize it to a java class that looks like this:
class Response
{
public StatusObject Status;
public String Data;
}
But FlexJson sees an object as the data attribute and then tries to cast a HashMap to my Data string. If I get a response back with 'null' as the Data attribute, everything works just fine (since you can assign null to a String).
How do I go about telling FlexJson to not try to make a HashMap out of the Data attribute and just take it as a String (even if it is a JSON object)?
Right now my deserialization line of code looks like this:
formattedResponse = new JSONDeserializer<network.Response>()
.use( "values", network.Response.class )
.deserialize(JSONString, network.Response.class);
Thank you for any help!
Solution
That's difficult because it parses the JSON into an intermediate form before it starts binding it into the object. So it's already parsed into a HashMap before it starts interrogating the object for what types it should use. If you wanted to put it into a string you'll have turn it back into JSON. You can do that using a ObjectFactory and binding that onto the path in your object. Inside the ObjectFactory it could then turn that into the string and bind that into the object there.
new JSONDeserializer<...>()
.use( "values", Response.class )
.use( "values.Data", new JSONStringTransformer() )
.deserialize( json, Response.class );
OTHER TIPS
I had the same silly problem but I went down the road of writing my own ObjectFactory to solve it.
package mypackage
import flexjson.JSONSerializer;
import flexjson.ObjectBinder;
import flexjson.ObjectFactory;
import java.lang.reflect.Type;
public class JSONStringFactory implements ObjectFactory {
@Override
public Object instantiate(ObjectBinder objectBinder, Object o, Type type, Class aClass) {
return new JSONSerializer().deepSerialize(o);
}
}
In the client code you just have to use the factory like that:
MyDomainClass foo = new JSONDeserializer<MyDomainClass>()
.use("sillyJSONField", new JSONStringFactory())
.deserialize(requestJson, MyDomainClass.class);