Map JSON Fields to Java Class Fields

In this lesson, you will learn how to properly map JSON fields to Java class fields using the Jackson library.

How to map JSON fields to Java class fields?

When we are converting JSON to Java Object, the default behavior of Jackson is to map the JSON fields to the corresponding fields (fields with the same name) in the Java Object.

So, for example, if we have a JSON like this:

{
  "name": "John",
  "age": 31,
  "city": "London"
}


To convert it to Java Object we need to have a class like this one:

class Person {
  private String name;
  private int age;
  private String city;

  // Constructors, getters, setters and toString() method

}

Note: We need the default constructor, getters, and setters methods for the Jackson conversion. Jackson maps the fields by matching the names of the JSON fields to the getter and setter methods in the Java class.

In this case, Jackson will convert JSON to a Person object, and all the class fields will be populated with the corresponding values from the JSON. 

Let’s try it:

import com.fasterxml.jackson.databind.ObjectMapper;

class Test {

  public static void main(String[] args) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();

    String json = "{\"name\":\"John\",\"age\":31,\"city\":\"London\"}";

    Person person = objectMapper.readValue(json, Person.class);

    System.out.println("Person object: " + person);
  }
}
Output: Person object: Person{name=’John’, age=31, city=’London’}
 
When converting the Person object to JSON, we will get the JSON that contains fields with the same names as the fields in the Person class.

Example:

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

class Test {

  public static void main(String[] args) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();

    Person person = new Person("Megan", 28, "New York");

    JsonNode personAsJSON = objectMapper.convertValue(person, JsonNode.class);

    System.out.println("Person object as JSON: \n" + personAsJSON.toPrettyString());
  }
}
Output: Person object as JSON: { “name” : “Megan”, “age” : 28, “city” : “New York” }
 
See here how to set up Jackson to ignore unknown JSON fields.
 
Happy coding!

Leave a Reply

Your email address will not be published.