- How To Convert A Java Object To Json
- 1.2. Source code
- 1. Convert A Java Object To JSON With Jackson
- 1.1. Jackson Library Dependency
- 1.2. Convert a Java object to JSON with Jackson
- 1.3. Convert a Java collection to Json with Jackson
- 1.4. Convert a Java Map to Json with Jackson
- 1.5. Customize Jackson
- 1.5.1. Change Date Time Format With Jackson
- 1.5.2. Change Date Format With Jackson
- 1.5.3. Change LocalDate Format With Jackson
- 2. Convert A Java Object To Json With Gson
- 2.1. Gson Library Dependency
- 2.2. Convert A Java Object To Json With Gson
- 2.3. Convert A Java List To Json With Gson
- 2.4. Convert A Java Set To Json with Gson
- 2.5. Convert a Java Map to Json with Gson
- 3. Conclusion
- howtoprogram
- Convert list of objects to/from JSON in java (jackson objectmapper/ example)
- 1. Jackson objectMapper maven dependencies
- 2. Convert list of objects to/from JSON in java (jackson objectmapper)
- 2.1. Person Class:
- 2.2. JSONListConverter Class:
- Download Example Code – Jackson List Object to JSON
- 3. Output – list of objects to/from JSON in java (jackson objectmapper)
- Example — Convert List to JSON Array Using Jackson
- JacksonListToJson.java
- Output:
- Related Jackson JSON Examples
- Serialize/ convert list of objects to/from json in java (Gson & example)
- Program – convert list of objects to/from json in java (GSON & example)
- 1.) Person Class:
- 2.) JSONConverter Class:
- Download Code – convert list of objects to/from json (GSON)
- Output – convert list of objects to/from json in java (GSON & example)
- You may also like:
How To Convert A Java Object To Json
Firstly, let’s see a POJO class which will be converted to JSON for all our examples.
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. 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. 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:
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:
Let’s see the JSON output of the object:
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:
Let’s see the JSON string of the collection:
To make the JSON string looks better, we can use the ObjectWriter to serialize the objects using the default pretty printer for indentation:
The Json output now looks better:
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:
And now let’s see the console’s output:
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:
The JSON with pretty print is:
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:
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.
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:
Secondly, we will need to register capability of serializing java.time objects with the Jackson core:
Lastly, let’s specify our desired format of the LocalDate field in the POJO class by annotating it with the @JsonFormat annotation :
Let’s see the output on the console:
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:
2.2. Convert A Java Object To Json With Gson
Firstly, let’s convert a Java object to Json using Gson:
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:
The JSON string output is:
2.3. Convert A Java List To Json With Gson
Next, let’s convert a java.util.List to Json with Gson:
Let’s see the JSON output of the list is:
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:
And see the output of the Set in Json:
2.5. Convert a Java Map to Json with Gson
And now, let’s convert a java.util.Map to Json with Gson:
The JSON output of the Map is:
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:
howtoprogram
private Long id;
private String name;
private String author;
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.
Convert list of objects to/from JSON in java (jackson objectmapper/ example)
1. Jackson objectMapper maven dependencies
com.fasterxml.jackson.core jackson-databind 2.7.1
2. Convert list of objects to/from JSON in java (jackson objectmapper)
2.1. Person Class:
package org.learn; public class Person < public String firstName; public String lastName; public int age; public Person() < >public Person(String firstName, String lastName, int age) < this.firstName = firstName; this.lastName = lastName; this.age = age; >public String toString() < return "[" + firstName + " " + lastName + " " + age +"]"; >>
2.2. JSONListConverter Class:
JSONListConverter class is responsible for performing following operations.
package org.learn; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; public class JSONListConverter < public static void main( String[] args ) throws IOException < ObjectMapper objectMapper = new ObjectMapper(); //Set pretty printing of json objectMapper.enable(SerializationFeature.INDENT_OUTPUT); //Define map which will be converted to JSON ListpersonList = Stream.of( new Person("Mike", "harvey", 34), new Person("Nick", "young", 75), new Person("Jack", "slater", 21 ), new Person("gary", "hudson", 55)) .collect(Collectors.toList()); //1. Convert List of Person objects to JSON String arrayToJson = objectMapper.writeValueAsString(personList); System.out.println("1. Convert List of person objects to JSON :"); System.out.println(arrayToJson); //2. Convert JSON to List of Person objects //Define Custom Type reference for List type TypeReferencemapType = new TypeReference
() <>; List jsonToPersonList = objectMapper.readValue(arrayToJson, mapType); System.out.println("\n2. Convert JSON to List of person objects :"); //Print list of person objects output using Java 8 jsonToPersonList.forEach(System.out::println); > >
Download Example Code – Jackson List Object to JSON
3. Output – list of objects to/from JSON in java (jackson objectmapper)
1. Convert List of person objects to JSON : [ < "firstName" : "Mike", "lastName" : "harvey", "age" : 34 >, < "firstName" : "Nick", "lastName" : "young", "age" : 75 >, < "firstName" : "Jack", "lastName" : "slater", "age" : 21 >, < "firstName" : "gary", "lastName" : "hudson", "age" : 55 >] 2. Convert JSON to List of person objects : [Mike harvey 34] [Nick young 75] [Jack slater 21] [gary hudson 55]
Example — Convert List to JSON Array Using Jackson
The following example shows how to convert List object to JSON array using the ObjectMapper.writeValueAsString() method.
JacksonListToJson.java
package net.javaguides.jackson; import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; /** * Using Jackson API for list serialization and deserialization * @author ramesh fadatare * */ public class JacksonListToJson < public static void main(String[] args) throws JsonProcessingException < // Create ObjectMapper object. ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); List String > progLangs = new ArrayList < >(); progLangs.add("C"); progLangs.add("C++"); progLangs.add("Java"); progLangs.add("Java EE"); progLangs.add("Python"); progLangs.add("Scala"); progLangs.add("JavaScript"); // Serialize Object to JSON. String json = mapper.writeValueAsString(progLangs); // Print json System.out.println(json); > >
Output:
[ "C", "C++", "Java", "Java EE", "Python", "Scala", "JavaScript" ]
Related Jackson JSON Examples
Serialize/ convert list of objects to/from json in java (Gson & example)
Program – convert list of objects to/from json in java (GSON & example)
1.) Person Class:
- Person class containing firstName, lastName, age etc.
- We have overloaded toString method to print person information.
package org.learn.gson; public class Person < public String firstName; public String lastName; public int age; public String contact; public Person(String firstName, String lastName, int age, String contact) < this.firstName = firstName; this.lastName = lastName; this.age = age; this.contact = contact; >public String toString() < return "[" + firstName + " " + lastName + " " + age + " " +contact +"]"; >>
2.) JSONConverter Class:
JSONConverter is responsible for performing following operations.
package org.learn.gson; import java.lang.reflect.Type; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; public class JSONConverter < public static void main( String[] args ) < Gson objGson = new GsonBuilder().setPrettyPrinting().create(); List personList = Stream.of( new Person("Mike", "harvey", 34, "001894536"), new Person("Nick", "young", 75, "005425676"), new Person("Jack", "slater", 21 ,"009654153"), new Person("gary", "hudson", 55,"00564536"), new Person("Mike", "harvey", 21 ,"003685417"), new Person("gary", "hudson", 25,"00452341")) .collect(Collectors.toList()); //Convert list to json System.out.println("1. Convert list of person objects to Json"); String json = objGson.toJson(personList); System.out.println(json); //Convert json back to list System.out.println("2. Convert JSON to list of person objects"); Type listType = new TypeToken() <>.getType(); List readFromJson = objGson.fromJson(json, listType); readFromJson.forEach(System.out::println); > >
Download Code – convert list of objects to/from json (GSON)
Output – convert list of objects to/from json in java (GSON & example)
1. Convert list of person objects to Json [ < "firstName": "Mike", "lastName": "harvey", "age": 34, "contact": "001894536" >, < "firstName": "Nick", "lastName": "young", "age": 75, "contact": "005425676" >, < "firstName": "Jack", "lastName": "slater", "age": 21, "contact": "009654153" >, < "firstName": "gary", "lastName": "hudson", "age": 55, "contact": "00564536" >, < "firstName": "Mike", "lastName": "harvey", "age": 21, "contact": "003685417" >, < "firstName": "gary", "lastName": "hudson", "age": 25, "contact": "00452341" >] 2. Convert JSON to list of person objects [Mike harvey 34 001894536] [Nick young 75 005425676] [Jack slater 21 009654153] [gary hudson 55 00564536] [Mike harvey 21 003685417] [gary hudson 25 00452341]