JavaScript Object Notation
경량화 되어 있는 하나의 데이터 형식.
서로 다른 언어들간에 데이터를 주고받을 수 있도록 만들어진 텍스트 기반의 형식.
- { } 로 감싸져 있는 것
- 1개의 Object
{
"name" : "홍길동",
"age" : 25
}
[ ]로 감싸져 있는 것
{
"person1": [
{
"name" : "홍길동",
"age" : 25
},
{
"name" : "이순신",
"age" : 30
}
]
}
google 에서 만든 json 파싱 라이브러리 이다. 그래서 gson인가..?? (google + json)
JsonParser jsonParser = new JsonPareser();
String json =
"{'fruit': [
{'NO':1,'NAME':'APPLE','KOR':'사과','PRICE':'1000'},
{'NO':2,'NAME':'BANANA','KOR':'바나나','PRICE':'500'}
],
'animal': [
{'NO':1,'NAME':'cat','KOR':'고양이','age':'3'},
{'NO':2,'NAME':'dog','KOR':'개','age':'5'},
]}";
JsonParser jsonParser = new JsonPareser();
//예시의 경우 먼저 Object로 감싸져 있다.
JsonObject jsonObject = new (JsonObject) jsonParser.parse(json);
JsonArray jsonArray = (JsonArray) jsonObject.get("fruit");
//jsonArray에서의 첫번째 Object
JsonObject firstObj = (JsonObject) jsonArray.get(0);
//firstObj에서 NAME값 가져오기
String name = firstObj.get("NAME").getAsString();
//firstObj.get("NAME")은 Obejct이기 때문에 .getAsString()을 붙여서 String으로 변환
주의✅
String name = firstObj.get("NAME").toString();이렇게 할 경우 큰따옴표 두개가 생긴다.
그러므로 .getAsString()으로 받아야 한다.