☕️ java

Java JSON 파싱

beomsic 2022. 10. 7. 19:02

Java를 이용하여 JSON 파싱을 해보자

JSON Parser


JSON 파일을 땡겨와서 이를 저장하기 위해서 JSON 데이터를 사용해야 한다.

  • JSONObject
  • JSONArray

를 사용할 수 있다.

JSON-Simple

json-simple 라이브러리는 JSON 파싱을 지원한다.

  • org.json.simple.JSONObject

build.gradle

implementation group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'

JSONObject

객체(주로 String)을 Json 객체로 바꿔주거나 Json 객체를 새로 만드는 역할

 

JSONArray

Json들이 들어 있는 Array

JSONObject 사용

jsonObject = new JSONObject();
    
jsonObject.put("name", "beomsic");
jsonObject.put("OS", "iOS");
jsonObject.put("age", 11);

System.out.println(jsonObject.toJSONString());

JSONObject 객체를 만들고 put 메소드를 사용해 데이터를 넣어준다.

toJSONString() 메소드를 이용해 JSON 포맷 문자열 데이터로 만들어 준다.

만들어진 json 데이터들의 값은 put 메소드로 입력한 순서와 관계없이 출력된다.

  • HashMap 클래스를 상속받고 있다.
  • HashMap처럼 JSONObject에 추가한 엔트리의 값의 순서는 보장되지 않는다.

JSONObject 객체 생성시 HashMap 객체를 받을 수 있다.

HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("Name", "beomsic");
hashMap.put("OS", "iOS");
hashMap.put("age", "11");
        
JSONObject jsonObject = new JSONObject(hashMap);
        
System.out.println(jsonObject.toJSONString());

JSONArray 사용

  • JSONObject - 객체를 다룸
  • JSONArray - JSON 배열을 다룸
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("Name", "beomsic");
hashMap.put("OS", "iOS");
hashMap.put("age", "11");
JSONObject beomsic = new JSONObject(hashMap);

hashMap = new HashMap<>();
hashMap.put("Name", "kim");
hashMap.put("OS", "Android");
hashMap.put("age", "11");
JSONObject kim = new JSONObject(hashMap);

JSONArray jsonArray = new JSONArray();
jsonArray.add(beomsic);
jsonArray.add(kim);

System.out.println(jsonArray.toJSONString());

JSONObject 객체들을 만들어 데이터를 설정하고 JSONArray 객체에 add() 메소드로 추가하면 JSONArray 객체를 생성할 수 있다.

JSONParser 사용

JSON 포맷의 문자열을 파싱하여 JSONObject로 생성 후 자바 로직에서 데이터 사용

String jsonString = "{\"name\":\"beomsic\",\"OS\":\"iOS\",\"age\":\"11\",\"Name\":\"kim\"}";

jsonParser = new JSONParser();

try {
  Object result = jsonParser.parse(jsonString);

  if (result instanceof JSONObject) {
    jsonObject = (JSONObject)result;
    System.out.println(jsonObject.toJSONString());
    
  }
  else if (result instanceof JSONArray) {
     jsonArray = (JSONArray)result;
     System.out.println(jsonArray.toJSONString());
     
   }
} catch (ParseException e) {
  e.printStackTrace();
}

JSON 포맷 문서를 JSONParser 객체의 parse() 메소드를 이용해서 파싱한다.

instanceof 연산을 이용해 클래스를 파악하고 캐스팅해서 사용하면 된다.

참고 자료

https://hbase.tistory.com/184

https://code.google.com/archive/p/json-simple/