com.fasterxml.jackson.databind.ObjectMapper Example

Q

How to use com.fasterxml.jackson.databind.ObjectMapper class?

✍: FYIcenter.com

A

com.fasterxml.jackson.databind.ObjectMapper class allows you to map a JSON message to a Java class object that matches the JSON property structure.

Here is an example Java program, ObjectMapperTest.java:

// ObjectMapperTest.java
// Copyright (c) FYIcenter.com

import com.fasterxml.jackson.databind.ObjectMapper;
public class ObjectMapperTest {
  public static void main(String[] args) throws Exception {
    String json 
      = "{ \"name\": \"John Smith\","
      + " \"married\": false,"
      + " \"age\": 25,"
      + " \"phone\": null"
      + " }";
    ObjectMapper mapper = new ObjectMapper();
    Person person = mapper.readValue(json, Person.class);
    System.out.println(person);
  }

  public static class Person {
    private String name;
    private boolean married;
    private int age;
    private String phone;

    public void setName(String name) {
      this.name = name;
    }
    public void setMarried(boolean married) {
      this.married = married;
    }
    public void setAge(int age) {
      this.age = age;
    }
    public void setPhone(String phone) {
      this.phone = phone;
    }
    public String toString(){
      return name+", "+age+", "+married+", "+phone;
    }
  }
}

Run this Java program with 3 Jackson JAR files:

fyicenter$ java -cp jackson-core-2.12.4.jar: \
  jackson-databind-2.12.4.jar: \
  jackson-annotations-2.12.4.jar \
  ObjectMapperTest.java

John Smith, 25, false, null

The Java program mapped a JSON message to a Java class object correctly.

 

⇒ com.fasterxml.jackson.databind.ObjectWriter Example

⇐ Using Jackson Java JSON library

⇑ Using Jackson Java JSON library

⇑⇑ Jackson - Java JSON library

2021-08-11, 229👍, 0💬