How to deserialize the next json using Jackson

I have the following json:

{ "id":"myid", "fields":{ "body":"text body" } } 

which I want to deserialize into the following Java class:

 class TestItem { private String id; private String body; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } 

using the Jackson Json deserializer. This does not work because the body field is nested inside the fields inner class.

I cannot change the json structure, so is there any way (possibly using annotations), can I reassign the body field from TestItem.fields.body to TestItem.body ?

Edit: I had to say that this is part of a larger class hierarchy, and the goal of this exercise is to reduce its depth. In other words, I know that I CAN declare an inner class and then access it, but I did not achieve this.

+6
java json jackson
source share
1 answer

There are several feature requests that (if implemented) will limit the one-level wrap / unroll. But there is currently no declarative way to do this. And to some extent this is a marginal case, since it concerns data conversion as opposed to data binding (unfortunately, I can’t think of good libs object conversions, so there may be a bit of space).

Thus, two-phase binding is usually done: first into intermediate types (often java.util.Map, or Jackson JsonNode (tree model)); change them and then convert from this type to the actual result. For example, something like this:

 JsonNode root = mapper.readTree(jsonSource); // modify it appropriately (add, remove, move nodes) MyBean bean = mapper.convertValue(root, MyBean.class); 
+5
source share

All Articles