com.fasterxml.jackson.databind.ObjectWriter Example

Q

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

✍: FYIcenter.com

A

com.fasterxml.jackson.databind.ObjectWriter class allows you to map a Java class object to a JSON message in a pretty format.

Here is an example Java program, ObjectMapperWriter.java:

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

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
public class ObjectMapperWriter {
  public static void main(String[] args) throws Exception {
    Person person = new Person();
    ObjectMapper mapper = new ObjectMapper();
    ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
    String json = writer.writeValueAsString(person);
    System.out.println(json);
  }

  public static class Person {
    private String name = "John Smith";
    private boolean married = false;
    private int age = 25;
    private String phone = null;

    public String getName() {
      return this.name;
    }
    public boolean getMarried() {
      return this.married;
    }
    public int getAge() {
      return this.age;
    }
    public String getPhone() {
      return this.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 \
  ObjectMapperWriter.java

{
  "name" : "John Smith",
  "married" : false,
  "age" : 25,
  "phone" : null
}

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

 

⇒ com.fasterxml.jackson.dataformat.xml.XmlMapper Example

⇐ com.fasterxml.jackson.databind.ObjectMapper Example

⇑ Using Jackson Java JSON library

⇑⇑ Jackson - Java JSON library

2021-08-11, 257👍, 0💬