In this lesson, you will learn how to convert Java Object to JSON. We will use the ObjectMapper class from the Jackson library.
Convert Java Object to JSON
The ObjectMapper class contains two methods for parsing the Java Objects to and from JSON: convertValue() and readValue().
Let’s see how to parse Java Object to JSON using both methods.
Converting Java Object to JSON using the convertValue() method
First, we will create a User class:
class User { private String name; private String id; private boolean isPremium; public User(String name, String id, boolean isPremium) { this.name = name; this.id = id; this.isPremium = isPremium; } public String getName() { return name; } public String getId() { return id; } public boolean isPremium() { return isPremium; } }
The class that we want to parse to JSON needs to have getters because Jackson maps the fields by matching the names of the JSON fields to the getters and setters methods in the Java object.
Now, let’s convert a user object to JSON:
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; class Test { public static void main(String[] args) { ObjectMapper objectMapper = new ObjectMapper(); User user = new User("John", "12345UUID", true); JsonNode json = objectMapper.convertValue(user, JsonNode.class); System.out.println(json); } }
Parse Java Object to JSON using the readValue() method
We will use the same User class from the previous example. Since the readValue() method accepts JSON String as the first parameter, we need to convert the User object to a JSON String. For that, we will use the writeValueAsString() method.
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; class Test { public static void main(String[] args) throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); User user = new User("John", "12345UUID", true); // convert User object to JSON string String userAsJsonString = objectMapper.writeValueAsString(user); JsonNode json = objectMapper.readValue(userAsJsonString, JsonNode.class); System.out.println(json); } }