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 doesn't work because the body
field is nested inside a fields
inner class.
I can't change the json structure, so is there any way (perhaps using annotations) I can remap of the body
field up from TestItem.fields.body
to TestItem.body
?
Edit: I should have said this is part of a larger class hierarchy and the aim of the excercise is to reduce the depth of it. In other words, I know that I COULD declare an inner class and then access that, but that is not what I'm trying to achieve.
databind. ObjectMapper ) is the simplest way to parse JSON with Jackson. The Jackson ObjectMapper can parse JSON from a string, stream or file, and create a Java object or object graph representing the parsed JSON. Parsing JSON into Java objects is also referred to as to deserialize Java objects from JSON.
This is how i'm deserializing the date: SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); getObjectMapper(). getDeserializationConfig(). setDateFormat(dateFormat);
Deserialization annotations are used when we deserialize JSON string into an Object. Jackson library provides several deserialization annotations such as @JsonCreator, @JacksonInject, @JsonAnySetter, etc. These annotations are mostly used in setter. Let's understand each one of them one by one with an example.
There are couple of feature requests that (if implemented) would allow limited one-level wrapping/unwrapping. But currently there is no declarative way to do this. And to some degree it is edge case, since this goes into data transformation as opposed to data binding (unfortunately I can't think of good object transformation libs, so there may be bit of gap there).
What is usually done, then, is to do two-phase binding: first into intermediate types (often java.util.Map, or jackson JsonNode (Tree model)); modify those, and then convert from this type to 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With