Java JsonMapper-class And Method Code Example


Here is an example of how to use the JsonMapper class from the com.fasterxml.jackson.databind package in the Jackson library to convert a Java object to a JSON string:

import com.fasterxml.jackson.databind.JsonMapper;

public class Example {
    public static void main(String[] args) throws Exception {
        JsonMapper mapper = new JsonMapper();
        Person person = new Person("John", "Doe", 30);
        String json = mapper.writeValueAsString(person);
        System.out.println(json);
    }
}

class Person {
    private String firstName;
    private String lastName;
    private int age;

    public Person(String firstName, String lastName, int age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    // getters and setters...
}

In this example, the JsonMapper object is used to convert a Person object to a JSON string using the writeValueAsString() method. The resulting JSON string would look like this:

{"firstName":"John","lastName":"Doe","age":30}

Note that for this example, you also need to have jackson-databind dependency in your classpath.

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