JSON이란, Javascript Object Notaion의 약자로써, 자바스크립트 객체 표기법을 뜻하며
쉽게 생각하면 그냥 데이터 표현 방법이다. JSON은 실무에서도 굉장히 많이 쓰이니 꼭 알아 놓도록하자.
JSON의 구조는 크게 2가지인데, JSONObject와 JSONArray이다. 순서대로 알아보도록하다.
1. JSONObject
구조 : {"name", "shin", "age": 24}
사용방법 :
JSONObject jObj = new JSONObject;
jObj.put("name": "shin");
jObj.put("age": "24");
String input = jObj.toString();
input값 : {"name", "shin", "age": 24}
String data = jObj.get("name");
get값 : shin
2. JSONArray
구조 : [{"name":"shin"},{"name":"kang"}]
사용방법 :
String data = "[{\"Product\" : \"Mouse\", \"Maker\":\"Samsung\", \"Price\":23000},"
+ "{\"Product\" : \"KeyBoard\", \"Maker\":\"LG\", \"Price\":12000},"
+ "{\"Product\":\"HDD\", \"Maker\":\"Western Digital\", \"Price\":156000}]";
try{
String result = "";
JSONArray jArray = new JSONArray(data);
for (int i = 0; i < jArray.length(); i++){
JSONObject jObj = jArray.getJSONObject(i);
result += "product: " + jObj.getString("Product") + ", maker: " + jObj.getString("Maker") +
", price: " + jObj.getInt("Price") + "\n";
}
}catch (JSONException e){ }
결과값 : result : product: Mouse, maker: Samsung, price: 23000
product: KeyBoard, maker: LG, price: 12000
product: HDD, maker: Western Digital, price: 156000
출처 : http://biig.tistory.com/52
JSONObject 안에 Array를 넣어서 사용할수도 있다.
"jObj":{
"name" : "me",
"entuty":[
{"name":"shin"},
{"name":"kang"},
{"name":"choi"}
]
}
'Programming > Android' 카테고리의 다른 글
manifest (0) | 2016.09.02 |
---|---|
notification 고정시키기 (1) | 2016.08.28 |
AsyncTask (0) | 2016.08.26 |
AccessibilityService (0) | 2016.08.26 |
Intent와 Intent Filter (0) | 2016.08.26 |