on
[Java] json 파싱하기
[Java] json 파싱하기
JSON 라이브러리 다운
// Maven com.googlecode.json-simple json-simple 1.1.1 // Gradle implementation group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'
직접 다운로드
https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/json-simple/json-simple-1.1.1.jar
라이브러리 import
import org.json.simple.JSONObject; // JSON객체 생성 import org.json.simple.JSONArray; // JSON이 들어있는 Array 생성 import org.json.simple.parser.JSONParser; // JSON객체 파싱 import org.json.simple.parser.ParseException; // 예외처리
JSON 파싱
public class Sample{ // JSON을 파싱하기 위해서 ParseException가 필수적으로 필요하다 public static void main(String[] args) throws ParseException { // JSONObject 생성 JSONObject jsonObject1 = new JSONObject(); jsonObject1.put("name", "재횬"); jsonObject1.put("gender", "남"); jsonObject1.put("age", 28); // JSONObject 생성 JSONObject jsonObject2 = new JSONObject(); jsonObject2.put("name", "다욘"); jsonObject2.put("gender", "여"); jsonObject2.put("age", 26); // JSONArray 생성 및 array에 JSONObject 추가 JSONArray jsonArray = new JSONArray(); jsonArray.add(jsonObject1); jsonArray.add(jsonObject2); // JSONArray를 String으로 변환 String jsonStr = jsonArray.toJSONString(); System.out.println(jsonStr); /* 출력: [{"gender":"남","name":"재횬","age":28},{"gender":"여","name":"다욘","age":26}] */ // JSONParser를 이용해서 String으로된 JSON을 다시 JSONObject로 변환 JSONParser parser = new JSONParser(); JSONArray parsedJsonArray = (JSONArray) parser.parse(jsonStr); for (Object o: parsedJsonArray){ JSONObject jo = (JSONObject) o; System.out.println(jo.get("name")); } /* 출력: 재횬 다욘 */ } }
- JSONObject로 json형식의 Object를 만들 수 있다.
- JSONArray에 JSONObject를 추가할 수 있다.
- toJSONString() 메소드를 통해 json을 String으로 변환할 수 있다.
- JSONParser를 통해 String으로된 json을 JSONObject/JSONArray로 받을 수 있다.
이와 같은 성질을 이용해 json을 처리하면 된다.
from http://jhyonhyon.tistory.com/11 by ccl(A) rewrite - 2021-10-16 02:28:16