How to conditionally deserialize to a POJO field using Jackson?

Viewed 6660

How can I conditionally deserialize a JSON string to a POJO field?

I receive a JSON string like so:

{
 "status": "we stuck",
 "data" : "someData"
}

but "someData" can be just a string "under the bridge" or can be something like "['bridge 5', 'Mandela bridge']" or "[{'incident 1' : '['bridge 1', 'bridge 2]'},{'incident 2' : ['bridge 99', 'what ever else']}]"

I want to return the json string AS IS if "data" is an array then I will map to a different Type that deals with the array

I have a java class:

class Response {
  String status;
  String data;
}

the other Type will have data as

ArrayList<SomeOtherType> data;

This is what i have so far

 ObjectMapper mapper = new ObjectMapper();
 Response rspns = mapper.readValue(<theJSONStrHere>, Response.class);

this fails when data is an array, giving me the message

can not deserialize instance of java.lang.String out of START_ARRAY token

I don't know where to go from here.

3 Answers

You can use Custom Deserializer on a Method OR a Class using below :

extends JsonDeserializer

then

@Override
public ReturnObject deserialize(JsonParser parser, DeserializationContext ctx)
        throws IOException, JsonProcessingException {

        JsonToken token = parser.getCurrentToken();
        if(JsonToken.START_ARRAY.equals(token)){
        //TODO your JSON Array code handling
        }else{
        //TO DO you JSON Object Handling
        }
}
Related