How to convert Java object to JSON string?

The following example shows how to convert Java object into JSON string using Jackson. Jackson provide ObjectMapper class provides functionality to read and write JSON data. The writeValueAsString(Object) method to serialize any Java object into string.

Here are the steps to convert POJOs into JSON string:

  • Create a Java object, set some properties on it.
  • Creates a Jackson ObjectMapper that can read and write JSON, either to and from POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model.
  • Convert the Artist object artist into JSON by calling the writeValueAsString().
  • Print the json string.
package org.kodejava.jackson;

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

public class ObjectToJson {
    public static void main(String[] args) {
        Artist artist = new Artist();
        artist.setName("The Beatles");

        ObjectMapper mapper = new ObjectMapper();
        try {
            String json = mapper.writeValueAsString(artist);
            System.out.println("JSON = " + json);
        } catch (JsonProcessingException e) {

Running the code snippet above will print out the following result:

JSON = {"id":1,"name":"The Beatles"}

And here is the definition of Artist class.


public class Artist {
    private Long id;
    private String name;

    public Artist() {

    public Artist(Long id, String name) { = id; = name;

    // Getters & Setters

    public String toString() {
        return "Artist{" +
                "id=" + id +
                ", name='" + name + '\'' +

Maven Dependencies


Maven Central Maven Central Maven Central



Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.