Jackson ObjectMapper writeValueAsString() Example

1. Introduction

Jackson is a popular library for converting Java objects to JSON and vice versa. One of its core components is the ObjectMapper class, which provides functionality to read/write JSON. In this post, we'll explore the writeValueAsString() method of ObjectMapper, which is used to convert a Java object to its JSON string representation.

2. Example Steps

1. Create a Person class with a few attributes.

2. Instantiate an object of the Person class.

3. Use the ObjectMapper's writeValueAsString() method to convert the Person object to its JSON string representation.

4. Print the resultant JSON string.

3. Jackson ObjectMapper writeValueAsString() Example

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class WriteValueAsStringExample {

    public static class Person {
        private String name;
        private int age;
        private String address;

        // Constructors, getters, and setters are omitted for brevity.

        public Person(String name, int age, String address) {
            this.name = name;
            this.age = age;
            this.address = address;
        }
    }

    public static void main(String[] args) {
        Person person = new Person("John Doe", 30, "123 Elm Street");

        ObjectMapper mapper = new ObjectMapper();
        String jsonString = "";
        try {
            jsonString = mapper.writeValueAsString(person);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        System.out.println(jsonString);
    }
}

Output:

{"name":"John Doe","age":30,"address":"123 Elm Street"}

4. Step By Step Explanation

The ObjectMapper class is a fundamental part of the Jackson library, providing the functionality to convert between JSON and Java objects. The writeValueAsString() method, in particular, allows you to convert a Java object into its JSON representation as a string.

In the code above:

1. We defined a simple Person class with three attributes: name, age, and address.

2. We then instantiated a Person object.

3. We used an ObjectMapper instance and its writeValueAsString() method to convert the Person object to a JSON string.

4. The resulting JSON string is printed to the console.

It's essential to handle JsonProcessingException, which might be thrown if the Java object cannot be converted to JSON for some reason (e.g., due to invalid annotations or configuration).


Comments