Gson Java 개체를 JSON으로 변환하는 데 사용할 수 있는 라이브러리입니다. 대표. JSON 문자열을 동등한 Java 객체로 변환하는 데에도 사용할 수 있습니다. 사용할 기본 클래스는 Gson 입니다. new Gson()을 호출하여 만들 수 있습니다. 및 GsonBuilder 클래스를 사용하여 Gson 을 만들 수 있습니다. 인스턴스 .
우선 사람 을 생성하여 개체 목록을 변환할 수 있습니다. 클래스를 만들고 Person 개체 목록을 JSON으로 변환합니다.
예시
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
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
}
]