Search code examples
javastringjsonflexjson

How to force FlexJson in java to deserialize a json object to a string?


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 );