elevne's Study Note
Java Gson 본문
Gson 은 Java Object 를 JSON 으로 변환하는데 사용할 수 있는 Java 라이브러리이다. JSON 문자열을 동등한 Java 객체로 변환하는데에도 사용할 수 있다. 우선 아래와 같이 간단하게 User 클래스를 작성해본다.
package test_classes2;
public class User {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
위 클래스를 JSON 문자열로 변환하는 것은 매우 간단하다. 아래와 같이 진행한다.
import com.google.gson.Gson;
import test_classes.*;
import test_classes2.User;
public class Main {
public static void main(String[] args) {
Gson gson = new Gson();
User user = new User("John Doe", 30);
String json = gson.toJson(user);
System.out.println(json);
}
}
이 반대의 경우, 문자열을 User 객체로 만드는 것도 쉽게 가능하다. 아래와 같이 진행해볼 수 있다.
import com.google.gson.Gson;
import test_classes.*;
import test_classes2.User;
public class Main {
public static void main(String[] args) {
Gson gson = new Gson();
String json = "{\"name\":\"Jane Doe\",\"age\":25}";
User user = gson.fromJson(json, User.class);
System.out.println(user.getName());
System.out.println(user.getAge());
}
}
이러한 객체변환을 진행할 때 private 접근자의 필드들도 변환이 가능하며, 특정 어노테이션을 사용할 필요 없이 기본적으로 해당 클래스의 모든 필드들은 직렬화 및 역질렬화의 대상이 된다. (transient 를 사용하면 직렬화/역직렬화 대상에서 제외)
Gson 에서는 JsonElement 클래스가 사용된다. 이는 JSON 데이터 요소를 나타내는 추상클래스로, JsonObject, JsonArray, JsonPrimitive, JsonNull 클래스들의 부모 클래스이다. JsonElement 는 다양한 형식의 Json 데이터를 다룰 수 있도록 한다.
{
"name": "John Doe",
"age": 30,
"isMarried": false,
"hobbies": ["reading", "traveling"],
"address": {
"city": "New York",
"state": "NY"
}
}
위와 같은 JSON 데이터를 활용하여 JsonElement 의 다양한 메서드를 시험해볼 수 있다.
import com.google.gson.*;
import test_classes.*;
import test_classes2.User;
public class Main {
public static void main(String[] args) {
String json = "{\"name\":\"John Doe\",\"age\":30,\"isMarried\":false,\"hobbies\":[\"reading\",\"traveling\"],\"address\":{\"city\":\"New York\",\"state\":\"NY\"}}";
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(json);
System.out.println(element);
JsonObject object = element.getAsJsonObject();
System.out.println(object);
String name = object.get("name").getAsString();
System.out.println(name);
int age = object.get("age").getAsInt();
System.out.println(age);
boolean isMarried = object.get("isMarried").getAsBoolean();
System.out.println(isMarried);
JsonArray hobbies = object.get("hobbies").getAsJsonArray();
System.out.println(hobbies);
JsonObject address = object.get("address").getAsJsonObject();
System.out.println(address);
String city = address.get("city").getAsString();
System.out.println(city);
String state = address.get("state").getAsString();
System.out.println(state);
}
}
JsonObject 클래스 또한 JSON 객체를 나타내는 클래스이다. 위 예제에서 사용한 JSON 데이터는 JsonElement 로도, JsonObject 로도 변환이 될 수 있는 것이다. JsonObject 는 Map 과 유사한 구조를 가지고 있으며, key-value pair 로 이루어진 entrySet() 메서드와 각 키에 해당하는 값을 가져오는 get() 메서드를 제공한다.
import com.google.gson.*;
import test_classes.*;
import test_classes2.User;
public class Main {
public static void main(String[] args) {
JsonObject object = new JsonObject();
object.addProperty("name", "John Doe");
object.addProperty("age", 30);
object.addProperty("isMarried", false);
JsonArray hobbies = new JsonArray();
hobbies.add(new JsonPrimitive("reading"));
hobbies.add(new JsonPrimitive("traveling"));
object.add("hobbies", hobbies);
JsonObject address = new JsonObject();
address.addProperty("city", "New York");
address.addProperty("state", "NY");
object.add("address", address);
System.out.println(object.toString());
System.out.println(object.entrySet());
String name = object.get("name").getAsString();
int age = object.get("age").getAsInt();
System.out.println(name);
System.out.println(age);
}
}
위 코드에서는 addProperty() 메서드를 사용하여 key-value pair 들을 추가한다.
그 다음으로 JsonArray 클래스는 JSON 배열을 나타내는 클래스이다. JSON 배열은 대괄호 ([]) 로 시작하고 끝나며, 여러 값들을 쉼표로 구분하여 나열한다.
import com.google.gson.*;
import test_classes.*;
import test_classes2.User;
public class Main {
public static void main(String[] args) {
JsonArray array = new JsonArray();
array.add(new JsonPrimitive("red"));
array.add(new JsonPrimitive("green"));
array.add(new JsonPrimitive("blue"));
String color1 = array.get(0).getAsString();
String color2 = array.get(1).getAsString();
String color3 = array.get(2).getAsString();
System.out.println(color1 + " " + color2 + " " + color3);
}
}
위에서 계속 사용된 JsonPrimitive 클래스는 JSON 데이터에서 문자열, 숫자, boolean 값 등 원시값을 나타내는 클래스이다. 또, 마지막으로 JsonNull 클래스는 JSON 데이터에서 null 값을 나타내는 클래스이다. 이를 전부 활용하여 JSON 데이터를 생성해보면 아래와 같다.
import com.google.gson.*;
import test_classes.*;
import test_classes2.User;
public class Main {
public static void main(String[] args) {
JsonObject person1 = new JsonObject();
person1.addProperty("name", "John Doe");
person1.addProperty("age", 30);
JsonObject person2 = new JsonObject();
person2.addProperty("name", "Jane Doe");
person2.addProperty("age", 28);
JsonArray people = new JsonArray();
people.add(person1);
people.add(person2);
JsonObject result = new JsonObject();
result.add("people_data", people);
result.add("country", new JsonPrimitive("South Korea"));
result.add("null_test", JsonNull.INSTANCE);
System.out.println(result.toString());
}
}
이처럼 Gson 라이브러리를 활용하여 JSON 데이터를 쉽게 다룰 수 있는 것이다!
Reference:
'Backend > Java' 카테고리의 다른 글
Java (Singleton, 접근제어, Annotation) (0) | 2023.04.26 |
---|---|
Java (Primitive Type, Reference Type ~) (0) | 2023.04.25 |
Java Enum (0) | 2023.04.19 |
Java Functional Interface (0) | 2023.04.18 |
Thread, Future, ScheduledFuture, Runnable (0) | 2023.04.13 |