Gson Google에서 만든 Java용 json 라이브러리로 JSON 생성에 사용할 수 있습니다. . Gson을 사용하여 JSON을 생성하고 bean/java 객체를 변환할 수 있습니다. JSON 객체에. toJson()을 호출할 수 있습니다. Gson 의 방법 Java 개체를 JSON 개체로 변환하는 클래스입니다.
구문
public java.lang.String toJson(java.lang.Object src)
예시
import com.google.gson.Gson; public class ConvertJavaObjectToJSONTest { public static void main(String[] args) { Gson gson = new Gson(); Student student = new Student("Raja", "Ramesh", 30, "Hyderabad"); System.out.println(gson.toJson(student)); // converts java object to json object. } } // student class class Student { private String firstName; private String lastName; private int age; private String address; public Student(String firstName, String lastName, int age, String address) { super(); this.firstName = firstName; this.lastName = lastName; this.age = age; this.address = address; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String toString() { return "Student[ " + " firstName = " + firstName + ", lastName = " + lastName + ", age = " + age + ", address = " + address + " ]"; } }
출력
{"firstName":"Raja","lastName":"Ramesh","age":30,"address":"Hyderabad"}