본문 바로가기
카테고리 없음

[Java(자바)] json-simple (JSONObject, JSONArray, JSONParser)을 이용한 JSON 객체 다루기 예제

by 왕 달팽이 2019. 1. 15.
반응형

네트워크를 통해 데이터를 주고 받을 때 사람이 읽고 해석하기 쉬운 JSON 포맷을 많이 사용한다. 문자열의 형태로 데이터를 표현하는 JSON을 사용하기 위해 매 프로젝트마다 JSON 파싱과 Serialize 메소드를 매번 구현하는건 좀 귀찮다. 

 

Java를 사용하는 사용자라면 json-simple 이라는 라이브러리를 사용해 봤을 것이다.

 

json-simple 라이브러리 세팅

json-simple 라이브러리를 사용하기 위해서는 jar 파일이 필요하다. 메이븐(Maven)을 사용하는 유저라면 다음과 같은 Dependencies를 추가하면 쉽게 사용할 수 있다.

 

1
2
3
4
5
6
<!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>
cs

 

그래들(Gradle)을 사용하는 유저라면 그래들 설정을 추가하면 된다. 

 

1
2
// https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple
compile group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'
cs

 

mvnrepository.com에 가면 다른 설정들도 찾아볼 수 있다. (링크 : mvnrepository.com)

 

간단한 JSONObject를 이용한 JSON 객체 생성 예제

json-simple 라이브러리의 JSONObject 객체를 이용해 JSON 객체를 만들어보자. 

 

1
2
3
4
5
6
7
8
JSONObject jsonObject = new JSONObject();
 
jsonObject.put("Name""iPhone");
jsonObject.put("company""Apple");
jsonObject.put("OS""iOS");
jsonObject.put("category""Phone");
 
System.out.println(jsonObject.toJSONString());
cs

 

이 코드를 실행하면 다음 결과를 얻게 된다. 

 

{"OS":"iOS","company":"Apple","category":"Phone","Name":"iPhone"}

 

주목할 점은 put() 메소드를 이용해 추가한 순서대로 출력되지는 않는다는 점이다. JSONObject의 코드를 열어보면 HashMap 클래스를 extends 하고 있음을 알 수 있다. 따라서 해시값에 의한 순서로 출력이 되기 때문에 입력한 순서와 상관없는 순서로 만들어진다. 

 

추가로 이 코드를 IntelliJ 등의 IDE에 넣어보면 컴파일러 Warning을 보기도 한다.

 

Unchecked call to 'put(K, V)' as a member of raw type 'java.util.HashMap'

 

HashMap 클래스는 지네릭(Generic)을 이용하고 있다. 따라서 HashMap 클래스를 사용할 때는 Key와 Value의 클래스를 명시해야 한다. JSONObject 클래스는 HashMap 클래스를 상속했으므로 동일하게 Key와 Value에 대한 클래스 명시가 필요하다. 하지만 JSONObject 자체는 지네릭이 아니기 때문에 Key, Value의 타입을 명시할 수 없다. 

 

이 컴파일러 Warning을 피하려면 코드를 다음과 같이 짤 수 있다.

 

1
2
3
4
5
6
7
8
9
HashMap<StringString> hashMap = new HashMap<>();
hashMap.put("Name""iPhone");
hashMap.put("company""Apple");
hashMap.put("OS""iOS");
hashMap.put("category""Phone");
        
JSONObject jsonObject = new JSONObject(hashMap);
        
System.out.println(jsonObject.toJSONString());
cs

 

HashMap에 Key-Value 형태로 값을 지정하고, JSONObject 클래스의 생성자에 HashMap을 인자로 넣어주면 된다. 

 

JSONArray를 이용한 JSON 객체 배열 생성

JSONArray는 JSONObject의 배열이라고 생각하면 된다. JSONArray는 다음과 같이 사용할 수 있다. 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
HashMap<StringString> hashMap = new HashMap<>();
hashMap.put("Name""iPhone");
hashMap.put("company""Apple");
hashMap.put("OS""iOS");
hashMap.put("category""Phone");
JSONObject iphone = new JSONObject(hashMap);
 
hashMap = new HashMap<>();
hashMap.put("Name""Galaxy Note 9");
hashMap.put("company""Samsung");
hashMap.put("OS""Android");
hashMap.put("category""Phone");
JSONObject galaxyNote9 = new JSONObject(hashMap);
 
JSONArray jsonArray = new JSONArray();
jsonArray.add(iphone);
jsonArray.add(galaxyNote9);
 
System.out.println(jsonArray.toJSONString());
cs

 

여러개의 JSONObject를 만들어서 JSONArray에 add 하고 toJSONString() 메소드를 호출하면 다음과 같은 결과를 얻을 수 있다. 

 

[{"company":"Apple","OS":"iOS","category":"Phone","Name":"iPhone"},{"company":"Samsung","OS":"Android","category":"Phone","Name":"Galaxy Note 9"}]

 

이 코드의 경우에도 Compiler Warning이 뜨는데, @SuppressWarnings("unchecked") 어노테이션을 추가하면 Warning을 안 볼 수 있다. (JSONObject처럼 코드로 우회할 수 있는 방법을 알고 계신분들은 댓글로 ㅜㅜ)

 

문자열을 JSONObject 객체로.. JSONParser 

HashMap, ArrayList 같은 자바 객체에서 JSON 문자열을 만들어 내는 것이 JSONObject, JSONArray의 역할이었다면 JSONParser는 JSON 문자열에서 JSONObject 객체를 만들어내는 역할을 한다. 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
String jsonString = "{\"company\":\"Apple\",\"OS\":\"iOS\",\"category\":\"Phone\",\"Name\":\"iPhone\"}";
 
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject;
 
try {
    jsonObject = (JSONObject) jsonParser.parse(jsonString);
 
    String str = (String) jsonObject.get("company");
 
    System.out.println(str);
catch (ParseException e) {
    e.printStackTrace();
}
cs

 

위 코드를 보면 jsonString 변수를 파싱하여 JSONObject 객체를 얻는다. 그리고 JSONObject 클래스가 제공하는 메소드를 이용해서 특정 키의 값을 얻어왔다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
String jsonString = "[{\"company\":\"Apple\",\"OS\":\"iOS\",\"category\":\"Phone\",\"Name\":\"iPhone\"},{\"company\":\"Samsung\",\"OS\":\"Android\",\"category\":\"Phone\",\"Name\":\"Galaxy Note 9\"}]";
 
JSONParser jsonParser = new JSONParser();
JSONArray jsonArray;
 
try {
    jsonArray = (JSONArray) jsonParser.parse(jsonString);
 
    for (Object obj : jsonArray)
        System.out.println(((JSONObject)obj).get("Name"));
catch (ParseException e) {
    e.printStackTrace();
}
cs

 

JSONArray로도 파싱을 할 수 있다. 위 코드는 두 개의 JSON 객체를 담고 있는 JSON 문자열을 파싱하여 JSONArray 객체를 만들고, 이 객체에 접근해서 정보를 추출해내는 코드다. 

 

json-simple 라이브러리를 이용하여 JSON 객체를 쉽게 다룰 수 있다.

 

반응형

댓글