This tutorial is going to cover how to convert a Java object to JSON string and vice versa using both Jackson 2 and Gson libraries.
1. Preparation
1.1. POJO
Firstly, let’s see a POJO class which will be converted to JSON for all our examples.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
public class Book { private Long id; private String name; private String author; @JsonInclude(NON_NULL) private LocalDate pubDate; @JsonInclude(NON_NULL) private Date copyrightDate; public Book() { super(); } public Book(Long id, String name, String author) { super(); this.id = id; this.name = name; this.author = author; } //getters and setters } |
The Book has 3 fields: id, name, and author. Besides, it also has a default constructor, getters, and setters for all fields. Note that there are 2 fields annotated with @JsonInclude(NON_NULL) which is used to tell Jackson to ignore or not include annotated fields when their values are NULL or empty during Jackson’s serialization.
1 2 3 4 5 |
@JsonInclude(NON_NULL) private LocalDate pubDate; @JsonInclude(NON_NULL) private Date copyrightDate; |
1.2. Source code
The sample source code presented in this tutorial is available on Github. It’s a Maven based project, it should be easy to run or to be imported into IDE such as Eclipse, Intelli, etc.
1. Convert A Java Object To JSON With Jackson
This section is going to cover how to convert a Java object to JSON with Jackson 2, a very popular JSON library for Java.
1.1. Jackson Library Dependency
The only dependency of Jackson 2 library we need for all examples is:
1 2 3 4 5 |
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.0</version> </dependency> |
1.2. Convert a Java object to JSON with Jackson
Let’s assume that we have an object “shBook” and we want to convert that book to JSON:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
@Test public void testConvertObjectToJSON() throws JsonProcessingException { Book shBook = new Book(1l, "Sour Heart", "Jenny Zhang"); // Converts the shBook to JSON ObjectMapper mapper = new ObjectMapper(); String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(shBook); assertTrue(json.contains("Sour Heart")); assertTrue(json.contains("Jenny Zhang")); System.out.println(json); } |
To convert a Java object to JSON with Jackson, we need to create an ObjectMapper object and use its writeValueAsString method to serialize any Java value as a String. In the above example, we have used the writerWithDefaultPrettyPrinter method to serialize objects using the Jackson default pretty printer for indentation. If we don’t need the pretty print feature, to convert a Java object to JSON, we can simply call:
1 |
String json = mapper.writeValueAsString(shBook); |
Let’s see the JSON output of the object:
1 2 3 4 5 |
{ "id" : 1, "name" : "Sour Heart", "author" : "Jenny Zhang" } |
1.3. Convert a Java collection to Json with Jackson
We can also use the mapper.writeValueAsString method to convert a Java collection to JSON, for example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
@Test public void convertCollectionToJsonTest() throws JsonProcessingException { Book h2prBook = new Book(1l, "Java How To Program", "Paul Deitel"); Book thinkJavaBook = new Book(2l, "Thinking in Java", "Bruce Eckel"); List<Book> books = new ArrayList<Book>(); books.add(h2prBook); books.add(thinkJavaBook); // Converts the list to JSON ObjectMapper mapper = new ObjectMapper(); String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(books); assertTrue(json.contains(h2prBook.getName())); assertTrue(json.contains(thinkJavaBook.getName())); System.out.println(json); } |
Let’s see the JSON string of the collection:
1 2 |
[{"id":1,"name":"Java How To Program","author":"Paul Deitel"}, {"id":2,"name":"Thinking in Java","author":"Bruce Eckel"}] |
To make the JSON string looks better, we can use the ObjectWriter to serialize the objects using the default pretty printer for indentation:
1 2 |
ObjectMapper mapper = new ObjectMapper(); String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(books); |
The Json output now looks better:
1 2 3 4 5 6 7 8 9 |
[ { "id" : 1, "name" : "Java How To Program", "author" : "Paul Deitel" }, { "id" : 2, "name" : "Thinking in Java", "author" : "Bruce Eckel" } ] |
1.4. Convert a Java Map to Json with Jackson
Let’s assume we have a java.util.Map “bookMap” which its keys are the ids of books and values are the books themselves. And then let’s see how we convert the map to JSON in the below example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
@Test public void convertMapToJsonTest() throws JsonProcessingException { Book ilBook = new Book(1l, "The Immortalists", "Chloe Benjamin"); Book gdrmBook = new Book(2l, "The Girl Who Drank the Moon", "Kelly Barnhill"); Map<Long, Book> bookMap = new HashMap<Long, Book>(); bookMap.put(ilBook.getId(), ilBook); bookMap.put(gdrmBook.getId(), gdrmBook); // Converts the list to JSON ObjectMapper mapper = new ObjectMapper(); String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(bookMap); assertTrue(json.contains(ilBook.getName())); assertTrue(json.contains(gdrmBook.getName())); System.out.println(json); } |
And now let’s see the console’s output:
1 2 3 4 5 6 7 8 9 10 11 12 |
{ "1" : { "id" : 1, "name" : "The Immortalists", "author" : "Chloe Benjamin" }, "2" : { "id" : 2, "name" : "The Girl Who Drank the Moon", "author" : "Kelly Barnhill" } } |
1.5. Customize Jackson
1.5.1. Change Date Time Format With Jackson
When we convert a Java object to JSON with Jackson, there are some situations that we want to change the date time format of the output JSON. Before doing that, let’s see how a Date or LocalDate object in Java is serialized to JSON by default in the following example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Book capBook = new Book(1l, "Crime and Punishment", "Fyodor Dostoyevsky"); capBook.setPubDate(LocalDate.of( 2001, Month.AUGUST, 22)); capBook.setCopyrightDate(new Date()); try { ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(capBook); //pretty print json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(capBook); System.out.println(json); } catch (JsonProcessingException e) { e.printStackTrace(); } |
The JSON with pretty print is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
{ "id" : 1, "name" : "Crime and Punishment", "author" : "Fyodor Dostoyevsky", "pubDate" : { "year" : 2001, "month" : "AUGUST", "chronology" : { "id" : "ISO", "calendarType" : "iso8601" }, "dayOfMonth" : 22, "dayOfWeek" : "WEDNESDAY", "dayOfYear" : 234, "era" : "CE", "monthValue" : 8, "leapYear" : false }, "copyrightDate" : 1503814042173 } |
We can see that the field “pubDate” was printed very detail while to the field “copyrightDate” was converted to milliseconds before printing out.
Let’s customize Jackson so that we can have better formats of those date fields.
1.5.2. Change Date Format With Jackson
Let’s change the date format with Jackson by providing the ObjectMapper class a SimpleDateFormat instance as follow:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
Book capBook = new Book(1l, "Crime and Punishment", "Fyodor Dostoyevsky"); capBook.setPubDate(LocalDate.of( 2001, Month.AUGUST, 22)); capBook.setCopyrightDate(new Date()); try { ObjectMapper mapper = new ObjectMapper(); SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); mapper.setDateFormat(df); String json = mapper.writeValueAsString(capBook); //pretty print json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(capBook); System.out.println(json); } catch (JsonProcessingException e) { e.printStackTrace(); } |
We have created an instance of SimpleDateFormat class with a pattern: dd-MM-yyyy hh:mm:ss which should be used by Jackson when it serializes the copyrightDate into String.
1 2 |
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); mapper.setDateFormat(df); |
Let’s see the output JSON:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
{ "id" : 1, "name" : "Crime and Punishment", "author" : "Fyodor Dostoyevsky", "pubDate" : { "year" : 2001, "month" : "AUGUST", "chronology" : { "id" : "ISO", "calendarType" : "iso8601" }, "dayOfMonth" : 22, "dayOfWeek" : "WEDNESDAY", "dayOfYear" : 234, "era" : "CE", "monthValue" : 8, "leapYear" : false }, "copyrightDate" : "27-08-2017 01:21:25" } |
We can see that the copyrightDate field now has value “27-08-2017 01:21:25” instead of milliseconds.
1.5.3. Change LocalDate Format With Jackson
Setting SimplDateFormat works for java.util.Date class only. And we will need another way to change the LocalDate format with Jackson. Firstly, let’s add the following dependency into pom.xml file:
1 2 3 4 5 |
<dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jdk8</artifactId> <version>2.9.0</version> </dependency> |
Secondly, we will need to register capability of serializing java.time objects with the Jackson core:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
Book capBook = new Book(1l, "Crime and Punishment", "Fyodor Dostoyevsky"); capBook.setPubDate(LocalDate.of( 2001, Month.AUGUST, 22)); capBook.setCopyrightDate(new Date()); try { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JavaTimeModule()); String json = mapper.writeValueAsString(capBook); //pretty print json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(capBook); System.out.println(json); } catch (JsonProcessingException e) { e.printStackTrace(); } |
Lastly, let’s specify our desired format of the LocalDate field in the POJO class by annotating it with the @JsonFormat annotation :
1 2 3 |
@JsonFormat(pattern = "dd/MM/yyyy") @JsonInclude(NON_NULL) private LocalDate pubDate; |
Let’s see the output on the console:
1 2 3 4 5 6 7 |
{ "id" : 1, "name" : "Crime and Punishment", "author" : "Fyodor Dostoyevsky", "pubDate" : "22/08/2001", "copyrightDate" : 1503816651745 } |
We can see that the pubDate now has format dd/MM/yyyy.
2. Convert A Java Object To Json With Gson
2.1. Gson Library Dependency
The only dependency of Gson library we need for all blow examples is:
1 2 3 4 5 |
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.1</version> </dependency> |
2.2. Convert A Java Object To Json With Gson
Firstly, let’s convert a Java object to Json using Gson:
1 2 3 4 5 6 7 8 9 10 |
@Test public void testConvertOjectToJsonTest() { Book milkHoneyBook = new Book(1000L, "Milk and Honey", "Rupi Kaur"); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(milkHoneyBook); assertTrue(json.contains("Milk and Honey")); System.out.print(json); } |
We have created a Gson object by using GsonBuilder class so that we can configure Gson to output Json that fits in a page for pretty printing. If we don’t need such pretty printing, we can create a Gson object simply as follows:
1 |
Gson gson = new Gson(); |
The JSON string output is:
1 2 3 4 5 |
{ "id": 1000, "name": "Milk and Honey", "author": "Rupi Kaur" } |
2.3. Convert A Java List To Json With Gson
Next, let’s convert a java.util.List to Json with Gson:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
@Test public void testConvertListToJsonTest() { Book sfBook = new Book(1001L, "StrengthsFinder 2.0", "Tom Rath"); Book pHBook = new Book(1002L, "The Power of Habit", "Charles Duhigg"); List<Book> books = new ArrayList<Book>(); books.add(sfBook); books.add(pHBook); // Converts the list to JSON Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(books); assertTrue(json.contains("StrengthsFinder 2.0")); assertTrue(json.contains("The Power of Habit")); System.out.println(json); } |
Let’s see the JSON output of the list is:
1 2 3 4 5 6 7 8 9 10 11 12 |
[ { "id": 1001, "name": "StrengthsFinder 2.0", "author": "Tom Rath" }, { "id": 1002, "name": "The Power of Habit", "author": "Charles Duhigg" } ] |
2.4. Convert A Java Set To Json with Gson
Let’s get to an example of converting a java.util.Set to Json with Gson:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
@Test public void testConvertSetToJsonTest() { Book litteFireBook = new Book(1001L, "Little Fires Everywhere", "Celeste Ng"); Book leoDaVinciBook = new Book(1002L, "Leonardo da Vinci", "Walter Isaacson"); Set<Book> books = new HashSet<Book>(); books.add(litteFireBook); books.add(leoDaVinciBook); // Converts the set to JSON Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(books); assertTrue(json.contains("Little Fires Everywhere")); assertTrue(json.contains("Leonardo da Vinci")); System.out.println(json); } |
And see the output of the Set in Json:
1 2 3 4 5 6 7 8 9 10 11 12 |
[ { "id": 1002, "name": "Leonardo da Vinci", "author": "Walter Isaacson" }, { "id": 1001, "name": "Little Fires Everywhere", "author": "Celeste Ng" } ] |
2.5. Convert a Java Map to Json with Gson
And now, let’s convert a java.util.Map to Json with Gson:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
@Test public void testConvertMapToJsonTest() { Book eoBook = new Book(1l, "Extreme Ownership", "Jocko Willink"); Book lopBook = new Book(2l, "The 48 Laws of Power", "Robert Greene"); Map<Long, Book> booksMap = new HashMap<Long, Book>(); booksMap.put(eoBook.getId(), eoBook); booksMap.put(lopBook.getId(), lopBook); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(booksMap); System.out.println(json); } |
The JSON output of the Map is:
1 2 3 4 5 6 7 8 9 10 11 12 |
{ "1": { "id": 1, "name": "Extreme Ownership", "author": "Jocko Willink" }, "2": { "id": 2, "name": "The 48 Laws of Power", "author": "Robert Greene" } } |
3. Conclusion
The tutorial has illustrated how to convert a Java object to JSON with Jackson and Gson. Below are other related tutorials for your references:
JsonObject Example – Getting Started with Java API for JSON Processing
Ignore Unknown Properties or New Fields in Jackson
Ignore or Exclude Field in Gson
Gson Example with Maven and Gradle
Makes no sense…
Why create a MODEL…
4
5
6
7
8
9
10
11
12
13
public class Book {
private Long id;
private String name;
private String author;
public Book() {
}
//getter and setter
}
and then reference the SAME data as static in the bean?
Sorry, not sure if I can catch your idea. The tutorial was mentioned with main points: to convert Java objects to JSON and vice versa. Let’s say that you wan to post a JSON string to a REST API and for some libraries like Apache Http Client or OKHttp client, you have to serialize the object (Book) into JSON string first. That’s the reason the Book classed was defined.
Note that the serialization/deserialization code is used in other classes, not in the Book class itself. You can refer to the example Github project for more detai.