Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json dynamic deserialization with jackson

I've already have a look at the question "Jackson dynamic property names" but it does not really answer to my question.

I want to deserialize something like this :

public class Response<T> {
    private String status;
    private Error error;
    private T data;
}

but data can have different names since different services exist and return the same structure with some different data. For example 'user' and 'contract' :

{
  response: {
    status: "success",
    user: {
        ...
    }
  }
}

or

{
  response: {
    status: "failure",
    error : {
        code : 212, 
        message : "Unable to retrieve contract"
    }
    contract: {
        ...
    }
  }
}

I'd like genericize my responses objects like this :

public class UserResponse extends Response<User> {}

I've tried the following but i'm not sure it is my use case or if don't use it in the good way :

 @JsonTypeInfo(include = As.WRAPPER_OBJECT, use = Id.CLASS)
 @JsonSubTypes({@Type(value = User.class, name = "user"),
                    @Type(value = Contract.class, name = "contract")})

Finally, i've created a custom Deserializer. It works but i'm not satisfied:

public class ResponseDeserializer extends JsonDeserializer<Response> {
@Override
public Response deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    Response responseData = new Response();
    Object data = null;

    for (; jp.getCurrentToken() != JsonToken.END_OBJECT; jp.nextToken()) {
        String propName = jp.getCurrentName();
        // Skip field name:
        jp.nextToken();

        if ("contract".equals(propName)) {
            data = mapper.readValue(jp, Contract.class);
        } else if ("user".equals(propName)) {
            data = mapper.readValue(jp, User.class);
        } else if ("status".equals(propName)) {
            responseData.setStatus(jp.getText());
        } else if ("error".equals(propName)) {
            responseData.setError(mapper.readValue(jp, com.ingdirect.dg.business.object.community.api.common.Error.class));
        }
    }

    if (data instanceof Contract) {
        Response<Contract> response = new Response<Ranking>(responseData);
        return response;
    }

    if (data instanceof User) {
        Response<User> response = new Response<User>(responseData);
        return response;
    }

    // in all other cases, the type is not yet managed, add it when needed
    throw new JsonParseException("Cannot parse this Response", jp.getCurrentLocation());
}

}

Any idea to do this clean with annotations ? Thanks in advance !

like image 853
Jerome VDL Avatar asked Sep 13 '13 13:09

Jerome VDL


People also ask

How does Jackson read nested JSON?

A JsonNode is Jackson's tree model for JSON and it can read JSON into a JsonNode instance and write a JsonNode out to JSON. To read JSON into a JsonNode with Jackson by creating ObjectMapper instance and call the readValue() method. We can access a field, array or nested object using the get() method of JsonNode class.


1 Answers

Jackson framework provides inbuilt support for dynamic types.

//Base type
@JsonTypeInfo(property = "type", use = Id.NAME)
@JsonSubTypes({ @Type(ValidResponse.class), 
                @Type(InvalidResponse.class) 
              })
public abstract class Response<T> {

} 
//Concrete type 1
public class ValidResponse extends Response<T>{

}
//Concrete type 2
public class InvalidResponse extends Response<T>{

}

main {
    ObjectMapper mapper = new ObjectMapper();
    //Now serialize
    ValidResponse response = (ValidResponse)(mapper.readValue(jsonString,      Response.class));

    //Deserialize
    String jsonString = mapper.writeValueAsString(response);
}
like image 82
Ajeet Avatar answered Sep 27 '22 21:09

Ajeet