This example show you how to convert Java collections object into JSON
string. For Student
class use in this example you can find it the previous example on How do I convert object into JSON?.
package org.kodejava.gson;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.kodejava.gson.support.Student;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class CollectionToJson {
public static void main(String[] args) {
// Converts a collection of string object into JSON string.
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Carol");
names.add("Mallory");
Gson gson = new Gson();
String jsonNames = gson.toJson(names);
System.out.println("jsonNames = " + jsonNames);
// Converts a collection Student object into JSON string
Student a = new Student("Alice", "Apple St", getDOB(2000, 10, 1));
Student b = new Student("Bob", "Banana St", null);
Student c = new Student("Carol", "Grape St", getDOB(2000, 5, 21));
Student d = new Student("Mallory", "Mango St", null);
List<Student> students = new ArrayList<>();
students.add(a);
students.add(b);
students.add(c);
students.add(d);
gson = new Gson();
String jsonStudents = gson.toJson(students);
System.out.println("jsonStudents = " + jsonStudents);
// Converts JSON string into a collection of Student object.
Type type = new TypeToken<List<Student>>() {
}.getType();
List<Student> studentList = gson.fromJson(jsonStudents, type);
for (Student student : studentList) {
System.out.println("student.getName() = " + student.getName());
}
}
private static Date getDOB(int year, int month, int date) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month - 1);
calendar.set(Calendar.DATE, date);
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
return calendar.getTime();
}
}
Here is the result of our program:
jsonNames = ["Alice","Bob","Carol","Mallory"]
jsonStudents = [{"name":"Alice","address":"Apple St","dateOfBirth":"Oct 1, 2000, 12:00:00 AM"},{"name":"Bob","address":"Banana St"},{"name":"Carol","address":"Grape St","dateOfBirth":"May 21, 2000, 12:00:00 AM"},{"name":"Mallory","address":"Mango St"}]
student.getName() = Alice
student.getName() = Bob
student.getName() = Carol
student.getName() = Mallory
Maven Dependencies
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.11.0</version>
</dependency>
Latest posts by Wayan (see all)
- How do I add an object to the beginning of Stream? - February 7, 2025
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024