JSON(JavaScript Object Notation) 소개
- Object를 인간이 읽을 수 있는 텍스트로 표현하는 방법 (Attribute-Value 방식)
- Attribute name: String Only
- Value: String, Number(e.g., int, float), Boolean, Null and Array of them.
JSON String 예제
# ex1
{"name":"dong"}
# ex2
{
"name":"dong",
"publicKey":["Base64String", "HexString"],
"index": 1
"signature": {
"algo":"ECDSA",
"curveParams":"secp256k1"
}
"isSet": true
}
- 장점
- 쉽다.
- 범용성: 대부분의 언어에서 JSON 처리 라이브러리를 지원함
- 단점
- 주석 지원하지 않음
- 형식이 틀리면 복구 불가
- value의 type을 기술할 방법 없음
- 단, 머신간 통신에서는 아무 문제 없음
Gson Package 소개
Gson은 Google에서 만든 JsonObject package. org.json package보다 활용성이 높다.
- 기존 org.json 패키지
- json String --> JSONObject(Map) 생성.
- JSONObject --> String
- Gson 패키지
- json String --> 특정 Class instance 생성.
- Instance --> String
기존에는 json String으로 특정 Instance를 생성하려면, json String으로 JSONObject를 생성하고 각 key로 value를 읽어와서 해당 Instance의 Constructor를 호출해야 했다. 반면 Gson 패키지를 이용하면 위와 같은 작업을 단 한줄로 끝낼 수 있다.
Gradle Dependency
#build.gradle의 dependencies에 다음 string을 추가.
compile group: 'com.google.code.gson', name: 'gson', version: '2.8.6'
예제
Example Class
public class Person {
public int age;
public String name;
public Date birthDate;
public boolean enrolled = false;
public Person() {
System.out.println("Constructor without param is called!!");
this.age = 50;
this.enrolled = true;
}
public Person(String name, int age, Date birthDate) {
System.out.println("Constructor with 2 params is called!!");
}
public static class Date {
public int y;
public int m;
public int d;
public Date() {}
}
}
Convert between jsonString and Instance
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class jsonTest {
public static void main(String[] args) {
String jsonString = "{'age':20, 'name':'dong', 'gender': 'M', 'birthDate': {'y':'2000','m':8, 'd':2}}";
Gson gson = new GsonBuilder().create();
Person person = gson.fromJson(jsonString, Person.class);
System.out.println(" name: "+person.name);
System.out.println(" age: "+person.age);
System.out.println("enroll: "+person.enrolled);
System.out.println("Date.y: "+ person.birthDate.y);
System.out.println("Date.m: "+ person.birthDate.m);
System.out.println("Date.d: "+ person.birthDate.d);
String result = gson.toJson(person, Person.class);
System.out.println("result: "+ result);
}
}
<Result>
Constructor without param is called!!!
name: dong
age: 20
enroll: true
Date.y: 2000
Date.m: 8
Date.d: 2
{"age":20,"name":"dong","birthDate":{"y":2000,"m":8,"d":2}, "enrolled":true}
- main line 1
- Person Class는 age, name, birthDate를 멤버로 갖으며, gender라는 멤버를 갖지 않는다.
- birthDate는 멤버 y, m, d를 갖는 Class이다.
- Person Class 구조와 맞지 않는 부분을 Gson이 어떻게 처리하는지 확인하고자 한다.
- main line 4
- jsonString 모든 key-value를 파싱하여 Person의 Constructor를 호출한다.
age, name, birthDate를 인자로 갖는 Constructor를 호출한다.(X)- 인자가 없는 기본 Constructor를 호출한다. (O)
- 그 후, 생성된 Instance의 각 멤버 변수에 값을 할당함.
- 작업 순서에 따라 Person()안에 "this.age = 50"이 무시됨 (덮어쓰기됨)
- Person.birthDate 객체도 Person과 같은 방식으로 생성됨.
- jsonString 모든 key-value를 파싱하여 Person의 Constructor를 호출한다.
- main line 6~11
- jsonString의 각 key-value는 Person 객체의 각 멤버에 적절하게 할당된다.
- 단, Person 객체가 가지고 있지 않은 gender는 무시된다.
- Person의 멤버인 "Date birthDate"는 {'y':2000, 'm':8, 'd':2}로 초기화 된다.
- main line13
- person 객체를 jsonString으로 출력함
- 출력 String을 보면 Person()이 호출된 것을 확인할 수 있음. (enrolled 멤버 값이 true로 변경됨.)
결론
기존 Json 패키지로 Gson의 모든 기능을 구현할 수 있으므로 반드시 Gson을 사용해야하는 것은 아니다. 하지만 코드 단 한 줄로 JsonString을 파싱하여 원하는 객체에 넣는 기능을 안쓸 이유도 없다. 그래서 앞으로 거의 Gson을 이용하게 될 것 같
'Dev. Tools' 카테고리의 다른 글
Git: Commit History 초기화 (0) | 2020.07.21 |
---|---|
Maven에서 Gradle로 갈아타기 (0) | 2020.07.21 |
Project Naming on IntelliJ: groupId, artifactId, version (0) | 2020.06.30 |