Close

Jackson JSON - Using @JsonRootName to customize POJO name to be serialized

[Updated: Sep 7, 2018, Created: Sep 7, 2018]

@JsonRootName annotation is used to indicate name of the POJO that should be serialized.

For serialization to work with @JsonRootName, SerializationFeature.WRAP_ROOT_VALUE should be enabled.
For deserialization DeserializationFeature.UNWRAP_ROOT_VALUE, should be enabled.

Example

POJO

@JsonRootName("Person")
public class PersonEntity {
  private String name;
  private int age;
    .............
}

Serializing and deserializing

public class ExampleMain {
  public static void main(String[] args) throws IOException {
      PersonEntity person = new PersonEntity("Jessie", 35);
      System.out.println("-- before serialization --");
      System.out.println(person);
      ObjectMapper om = new ObjectMapper();
      om.enable(SerializationFeature.WRAP_ROOT_VALUE);
      String jsonString = om.writeValueAsString(person);
      System.out.println("-- after serialization --");
      System.out.println(jsonString);

      om.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
      PersonEntity person2 = om.readValue(jsonString, PersonEntity.class);
      System.out.println("-- after deserialization --");
      System.out.println(person2);
  }
}
-- before serialization --
PersonEntity{name='Jessie', age=35}
-- after serialization --
{"Person":{"name":"Jessie","age":35}}
-- after deserialization --
PersonEntity{name='Jessie', age=35}

Without @JsonRootName

In above example, if we don't use @JsonRootName in PersonEntity class, then output will be:

-- before serialization --
PersonEntity{name='Jessie', age=35}
-- after serialization --
{"PersonEntity":{"name":"Jessie","age":35}}
-- after deserialization --
PersonEntity{name='Jessie', age=35}

Example Project

Dependencies and Technologies Used:

  • jackson-databind 2.9.6: General data-binding functionality for Jackson: works on core streaming API.
  • JDK 10
  • Maven 3.5.4

@JsonRootName Example Select All Download
  • jackson-json-root-name
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • PersonEntity.java

    See Also