선 조치 후 분석

GSON이란? 본문

ETC/IT Knowledge

GSON이란?

JB1104 2022. 10. 19. 14:54
728x90
반응형
SMALL

Gson(구글 Gson, Google Gson)은 'Google Gson'의 약어로 JSON의 자바 오브젝트의 직렬화, 역직렬화를 해주는 오픈 소스 자바 라이브러리이다.

 

즉, 자바 객체 ↔ JSON으로 변환할 때 사용하는 라이브러리

 

일반적으로 사용하는 메서드는 'toJson() ' 과 'fromJson()' 이 있다. 이름에서 알 수 있듯이 'Json'으로 변환할 때는 'toJson()' Java Object로 변환할 때는 'fromJson'을 사용한다.

 

그리고 크게 제네릭 타입인 경우와 제네릭 타입이 아닌 경우로 나뉘는 거 같다.

 

1. Non-Generic Type - toJson(Object)

Gson gson = new Gson(); // Or use new GsonBuilder().create();
MyType target = new MyType();
String json = gson.toJson(target); // serializes target to Json [Java Object -> Json]
MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2 [Json -> Java Object]

 

2.  Generic Type - toJson(Object src, Type typeOfSrc)

Type listType = new TypeToken<List<String>>() {}.getType();
List<String> target = new LinkedList<String>();
target.add("blah");

Gson gson = new Gson();
String json = gson.toJson(target, listType);
List<String> target2 = gson.fromJson(json, listType)

제네릭을 사용하는 경우에는 아래 내용을 참조해서 알아두자.

 

Object src : the object for which JSON representation is to be created (JSON 표현으로 변경되어야 할 객체)
Type typeOfSrc : The specific genericized type of src. You can obtain this type by using the TypeToken class.
(Object로 제네릭된 타입)

For example, to get the type for Collection <Foo>, you should use
Type typeOfSrc = new TypeToken <Collection <Foo>>(){}. getType();

728x90
반응형
LIST