Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deserialize the following json using Jackson

Tags:

java

json

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 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.

like image 952
Rupert Bates Avatar asked Mar 30 '11 10:03

Rupert Bates


People also ask

How do I deserialize a json object in Jackson?

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.

How does Jackson deserialize dates 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);

What is Jackson deserialization?

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.


1 Answers

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);
like image 77
StaxMan Avatar answered Sep 28 '22 10:09

StaxMan