Serializes Java object into JSON string using ObjectMapper.writeValueAsString() with Jackson

Tags: JSON jackson-databind Jackson

Java Code Examples for com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString()

This method can be used to serialize any Java object into a JSON String.

Adding Jackson dependency into your project

Using Gradle

compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.8'

Using Maven

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

How to use com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString()

package simplesolution.dev;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ObjectMapperWriteValueAsStringExamples {

    public static void main(String... args) {
        List<Map<String, String>> data = new ArrayList<>();
        Map<String, String> item1 = new HashMap<>();
        item1.put("name", "Sample JSON Serialization");
        item1.put("url", "https://simplesolution.dev");
        data.add(item1);

        Map<String, String> item2 = new HashMap<>();
        item2.put("name", "Java Tutorials");
        item2.put("url", "https://simplesolution.dev/java");
        data.add(item2);

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonStringFromObject = objectMapper.writeValueAsString(data);
            System.out.println("JSON String from Object: " + jsonStringFromObject);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Happy Coding 😊