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
ObjectMapperthat 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
Artistobjectartistinto JSON by calling thewriteValueAsString(). - Print the
jsonstring.
package org.kodejava.jackson;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.kodejava.jackson.support.Artist;
public class ObjectToJson {
public static void main(String[] args) {
Artist artist = new Artist();
artist.setId(1L);
artist.setName("The Beatles");
ObjectMapper mapper = new ObjectMapper();
try {
String json = mapper.writeValueAsString(artist);
System.out.println("JSON = " + json);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}
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.
package org.kodejava.jackson.support;
public class Artist {
private Long id;
private String name;
public Artist() {
}
public Artist(Long id, String name) {
this.id = id;
this.name = name;
}
// Getters & Setters
@Override
public String toString() {
return "Artist{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
Maven Dependencies
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.17.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.17.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.17.1</version>
</dependency>
</dependencies>

Thanks for sharing. Good luck!