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
objectartist
into JSON by calling thewriteValueAsString()
. - Print the
json
string.
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.15.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.15.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>
</dependencies>
Latest posts by Wayan (see all)
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023
Thanks for sharing. Good luck!