Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson : map nested object

Tags:

java

jackson2

Using jackson, i wonder if it's possible du map json to Java with nested Object that are not like the json structure.

Here an exemple of what i want to do.

Json :

{
  a = "someValue",
  b = "someValue",
  c = "someValue"
}

Java :

public class AnObject {
  @JsonProperty("a")
  private String value;

  //Nested object
  private SomeObject;
}

public class SomeObject {
  @JsonProperty("b")
  private String value1;

  @JsonProperry("c")
  private String value2;
}

Is it possible ?

like image 251
J.Mengelle Avatar asked Oct 05 '17 13:10

J.Mengelle


People also ask

How does Jackson read nested JSON?

A JsonNode is Jackson's tree model for JSON and it can read JSON into a JsonNode instance and write a JsonNode out to JSON. To read JSON into a JsonNode with Jackson by creating ObjectMapper instance and call the readValue() method. We can access a field, array or nested object using the get() method of JsonNode class.

What is the use of @JsonRootName?

@JsonRootName allows to have a root node specified over the JSON. We need to enable wrap root value as well.


2 Answers

Use the JsonUnwrapped annotation:

@JsonUnwrapped
private final SomeObject someObject;

which unwrappes all of SomeObject's fields into the parent, resulting in the following when serializing:

{"a":"foo","b":"bar","c":"baz"}
like image 134
Felk Avatar answered Oct 02 '22 14:10

Felk


Using ObjectMapper you can convert JSON string to Object. Use JsonUnwrapped in your AnObject class over someObject field.

@JsonUnwrapped
private SomeObject someObject;

then read JSON string and convert it to AnObject.

ObjectMapper mapper = new ObjectMapper();
try {
   AnObject anObject1 = mapper.readValue(jsonString, AnObject.class);   
} catch (IOException e) {
    e.printStackTrace();
}
like image 21
imk Avatar answered Oct 02 '22 12:10

imk