在Java中使用Gson库将对象列表转换为JSON
Gson是一个可用于将Java 对象转换为 JSON 表示形式的库。它还可用于将 JSON 字符串转换为等效的 Java 对象。要使用的主要类是Gson,我们可以通过调用new Gson()来创建它,并且GsonBuilder类可用于创建Gson实例。
我们可以通过首先创建一个Person类来转换对象列表,然后将JSON 格式的 Person 对象列表。
示例
import java.util.*; import java.util.stream.*; import com.google.gson.*; public class JSONConverterTest { public static void main( String[] args ) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); List list = Stream.of(new Person("Raja", "Ramesh", 30, "9959984800"), new Person("Jai", "Dev", 25, "7702144400"), new Person("Adithya", "Sai", 21, "7013536200"), new Person("Chaitanya", "Sai", 28, "9656444150")) .collect(Collectors.toList()); System.out.println("Convert list of person objects to Json:"); String json = gson.toJson(list); // converts to json System.out.println(json); } } // Person class<strong> </strong>class Person { private String firstName, lastName, contact; private int age; 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 +"]"; } }
输出
Convert list of person objects to Json: [ { "firstName": "Raja", "lastName": "Ramesh", "contact": "9959984800", "age": 30 }, { "firstName": "Jai", "lastName": "Dev", "contact": "7702144400", "age": 25 }, { "firstName": "Adithya", "lastName": "Sai", "contact": "7013536200", "age": 21 }, { "firstName": "Chaitanya", "lastName": "Sai", "contact": "9656444150", "age": 28 } ]
以上就是在Java中使用Gson库将对象列表转换为JSON的详细内容,更多请关注其它相关文章!