Java ObjectMapper-class And Method Code Example


Here is an example of how to use the ObjectMapper class from the com.fasterxml.jackson.databind package in Java:

import com.fasterxml.jackson.databind.ObjectMapper;

public class MyClass {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();

        // Example of deserializing JSON to a Java object
        MyObject obj = mapper.readValue("{\"name\":\"John\",\"age\":30}", MyObject.class);
        System.out.println(obj.getName()); // prints "John"
        System.out.println(obj.getAge()); // prints 30

        // Example of serializing a Java object to JSON
        String json = mapper.writeValueAsString(obj);
        System.out.println(json); // prints {"name":"John","age":30}

        // Example of deserializing JSON to a Map
        Map<String, Object> map = mapper.readValue("{\"name\":\"John\",\"age\":30}", new TypeReference<Map<String, Object>>(){});
        System.out.println(map.get("name")); // prints "John"
        System.out.println(map.get("age")); // prints 30
    }
}

class MyObject {
    private String name;
    private int age;

    // getters and setters
}

This example creates an instance of ObjectMapper. The ObjectMapper class is used to convert between JSON and Java objects. In this example, it is used to deserialize JSON into a MyObject instance and to serialize a MyObject instance to JSON. Also it shows how to deserialize JSON to a Map.

TypeReference is used to provide the type information for the mapping.

readValue method is used to deserialize JSON to a Java object or Map.

writeValueAsString method is used to serialize a Java object to a JSON string.