Deserting a field from nested objects in a JSON response using Jackson

It seems like this should be a pretty resolute / well-considered issue, but I do not find many recommendations on it - hoping this is not a hoax.

My scenario basically is that I consume paginated JSON responses that look something like this:

{ "objects": [...], "meta": { "total": 5000, "page": 1, "result_pages": 20, "links": { "prev": null, "next": "/api/v3/objects/somequery?page=2" } } } 

Obviously, this is simplified, but I hope it makes sense.

All I'm really interested in is the objects and next fields, but it looks like I need to create a whole DTO hierarchy to successfully deserialize the nested fields.

Is there an annotation for Jackson that would let me skip all this? If not, is there a set of best practices for this that does not include many mostly empty classes and files?

+7
java json jackson deserialization
source share
1 answer

Is there an annotation for Jackson that would let me skip all this?

You can use JsonDeserialize and define a custom JsonDeserializer.

 class MetaDeserializer extends JsonDeserializer<String> { @Override public String deserialize(JsonParser jp, DeserializationContext ctx) throws IOException { JsonNode tree = jp.readValueAsTree(); return tree.get("links").get("next").asText(); } } 

Here I used simple map deserialization, but if you want, you can implement your own quick deserialization.

And the object

 class MetaObject { public List<Integer> objects; @JsonDeserialize(using = MetaDeserializer.class) public String meta; @Override public String toString() { return "MetaObject{" + "objects=" + objects + ", meta='" + meta + '\'' + '}'; } } 

And if you call MetaObject result = mapper.readValue("...", MetaObject.class) , you will get what you want

 MetaObject{objects=[1, 2, 3], meta='/api/v3/objects/somequery?page=2'} 
+8
source share

All Articles