简体   繁体   中英

Jackson Data-Binding with Heterogeneous Json Object

I'm calling a rest service that returns a json object. I'm trying to deserialize the responses to my Java Beans using Jackson and data-binding.

The example Json is something like this:

{
    detail1: { property1:value1, property2:value2},
    detail2: { property1:value1, property2:value2},
    otherObject: {prop3:value1, prop4:[val1, val2, val3]}
}

Essentially, detail1 and detail2 are of the same structure, and thus can be represented by a single class type, whereas OtherObject is of another type.

Currently, I've set up my classes as follows (this is the structure I would prefer):

class ServiceResponse {
    private Map<String, Detail> detailMap;
    private OtherObject otherObject;

    // getters and setters
}

class Detail {
    private String property1;
    private String property2;

    // getters and setters
}

class OtherObject {
    private String prop3;
    private List<String> prop4;

    // getters and setters
}

Then, just do:

String response = <call service and get json response>
ObjectMapper mapper = new ObjectMapper();
mapper.readValue(response, ServiceResponse.class)

The problem is I'm getting lost reading through the documentation about how to configure the mappings and annotations correctly to get the structure that I want. I'd like detail1, detail2 to create Detail classes, and otherObject to create an OtherObject class.

However, I also want the detail classes to be stored in a map, so that they can be easily distinguished and retrieved, and also the fact that the service in in the future will return detail3, detail4, etc. (ie, the Map in ServiceResponse would look like "{detail1:Detail object, detail2:Detail object, ...} ).

How should these classes be annotated? Or, perhaps there's a better way to structure my classes to fit this JSON model? Appreciate any help.

Simply use @JsonAnySetter on a 2-args method in ServiceResponse, like so:

@JsonAnySetter
public void anySet(String key, Detail value) {
    detailMap.put(key, value);
}

Mind you that you can only have one "property" with @JsonAnySetter as it's a fallback for unknown properties. Note that the javadocs of JsonAnySetter is incorrect, as it states that it should be applied to 1-arg methods; you can always open a minor bug in Jackson ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM