本示例说明如何将Java集合对象转换为JSON字符串。对于Student在本示例中使用的类,您可以在前面的示例中找到如何将对象转换为JSON?
package org.nhooo.example.google.gson; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; 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) { // 将字符串对象的集合转换为JSON字符串。 List<String> names = new ArrayList<String>(); 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); // 将集合Student对象转换为JSON字符串 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<Student>(); 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); // 将JSON字符串转换为Student对象的集合。 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(); } }
这是我们程序的结果:
jsonNames = ["Alice","Bob","Carol","Mallory"] jsonStudents = [{"name":"Alice","address":"Apple St","dateOfBirth":"Nov 1, 3900 12:00:00 AM"},{"name":"Bob","address":"Banana St"},{"name":"Carol","address":"Grape St","dateOfBirth":"Jun 21, 3900 12:00:00 AM"},{"name":"Mallory","address":"Mango St"}] student.getName() = Alice student.getName() = Bob student.getName() = Carol student.getName() = Mallory
Maven依赖
<!-- http://repo1.maven.org/maven2/com/google/code/gson/gson/2.8.0/gson-2.8.0.jar --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.0</version> </dependency>