태그:

카테고리:

업데이트:


Java에서 JSON을 이용하기 위해서는 JSONObject를 이용합니다.

1. 라이브러리 Import 하기

import org.json.JSONObject;

2. 데이터 생성하기 (JSONObject)

JSONObject data = new JSONObject();
JSONObject sub_data = new JSONObject();

data.put("key", "value");
data.put("key2", 10);
data.put("key3", sub_data); // JSONObject에 JSONObject 추가

String json = data.toString(); // JSON 문자열 반환

3. 데이터 생성하기 (JSONArray)

JSONArray arr_data = new JSONOBject;
JSONObject sub_data = new JSONObject();

arr_data.put(sub_data); // append하는 기능

4. 데이터 파싱하기

JSONObject jObject = new JSONObject(json_str);          // {"key1": "abc", "key2": 123}와 같은 문자열
JSONArray jArray = new JSONArray(json_arr_str);         // [{"key1": 1}, {"key1": 2}]와 같은 문자열

String val = jObject.getString("key");                  // JSONObject에서 String값 가져오기
Integer num = jObject.getInt("key2");                   // JSONObject에서 int값 가져오기
JSONObject jobj = jObject.getJSONObject("key3");        // JSONObject에서 JSONObject가져오기
JSONArray jarr = jObject.getJSONArray("key4");          // JSONObject에서 JSONArray 가져오기

for(int i = 0; i < jarr.length(); i++) {
    JSONObject obj = jarr.getJSONObject(i);             // JSONArray에서 JSONObject 가져오기
}

댓글남기기