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

Tags: JSON jackson-databind Jackson

In this Java tutorial, we learn how to serializes an object into JSON String in Java using the ObjectMapper.writeValueAsString() method Jackson library.

Adding Jackson dependency into your project

Using Gradle

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

Using Maven


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

With Jackson library, we can use the com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString() method to serialize any Java object into a JSON String as the following example Java code.


import com.fasterxml.jackson.databind.ObjectMapper;

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", "");

        Map<String, String> item2 = new HashMap<>();
        item2.put("name", "Java Tutorials");
        item2.put("url", "");

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

Happy Coding 😊