Site icon

Convert JSON String to/from Java Object in Java (Jackson)

How to Parse JSON – Jackson Library?

We will use Jackson’s ObjectMapper to create a JSON object (ObjectNode) and a JSON array (ArrayNode). We then convert these structures to JSON strings for output and parse them back into JsonNode objects for input. We will demonstrates the process of creating, outputting, and inputting JSON objects and arrays using Jackson in Java. We will use Jackson Maven repository to use Jackson library.

Maven dependency of Jackson JSON Library

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.16.1</version>
</dependency>

Convert JSON to/from Java Object in Java (Jackson):

import com.fasterxml.jackson.databind.ObjectMapper;

class Manager {
    public String name;
    public int age;
    public Manager() {}
    public Manager(String name, int age) {
        this.name= name;
        this.age= age;
    }
    @Override
    public String toString() {
        return "Manager{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

public class JackJavaObjectToJSON {
    public static void main(String[] args) {
        // Create ObjectMapper
        ObjectMapper objectMapper = new ObjectMapper();
        Manager manager = new Manager("Mike",20);

        try {
            System.out.println("Java Object to JSON:");
            String json = objectMapper.writeValueAsString(manager);

            System.out.println(json);
            // Convert JSON String to Manager Object
            manager = objectMapper.readValue(json, Manager.class);

            System.out.println("\nJSON to Java Object using Jackson");
            // Access the Manager Object
            System.out.println(manager);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output:

JSON to Person:
Name: Mika
Age: 30
Person to JSON String:
{"name":"Mika","age":30}
Exit mobile version