Programming-[Backend]/Java

자바 Json 파싱, 값 추출하기 : JSONObject, JSONArray

컴퓨터 탐험가 찰리 2021. 12. 19. 18:01
728x90
반응형

1. Json 구조

 

 

Object 구조

 

Json 데이터를 파싱해서 가져오기 위한 첫 걸음은 Json의 구조를 이해하는 것이다. Json의 구조는 다음 3가지 방식이 있을 수 있다.

 

  1. JsonObject
  2. JsonObject 내부 JsonObject
  3. JsonArray

 

{ } - Culry bracket 으로 감싸진 것은 JsonObject,

[ ] - square bracket으로 감싸진 것은 JsonArray

 

 

필드값 규칙

 

key-value에서

 

key값은 반드시 쌍따옴표 " " 로 감싸야한다.

value 값은 Boolean이나 Integer는 그대로 쓰되, 나머지는 쌍따옴표 " "로 감싸야한다.

 

 

 


 

2. 예제 및 파싱해보기

 

예제 데이터

예제는 참조1의 데이터를 복사해왔다. batter의 id값들을 모두 추출해보자.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
{
    "id""0001",
    "type""donut",
    "name""Cake",
    "ppu"0.55,
    "batters":
        {
            "batter":
                [
                    { "id""1001""type""Regular" },
                    { "id""1002""type""Chocolate" },
                    { "id""1003""type""Blueberry" },
                    { "id""1004""type""Devil's Food" }
                ]
        },
    "topping":
        [
            { "id""5001""type""None" },
            { "id""5002""type""Glazed" },
            { "id""5005""type""Sugar" },
            { "id""5007""type""Powdered Sugar" },
            { "id""5006""type""Chocolate with Sprinkles" },
            { "id""5003""type""Chocolate" },
            { "id""5004""type""Maple" }
        ]
}
cs

 

 

 

 

파싱

 

new JsonObject("") 키워드의 " " 안에 복사한 JSONObject를 넣어주면된다. 그리고 구조에 따라 메서드를 적용하면 된다.

 

맨처음 JSONObject를 얻어오면 batters 또한 curly bracket { }으로 감싸져있는 JSONObject이므로, 29번줄과 같이 getJSONObject 문법을 사용하여 batters 객체를 얻어온다. 다음으로 batters 내부의 batter는 square barcket [ ]으로 이루어진 배열이므로, getJSONArray 문법을 사용한다. 배열 내부의 각 객체를 얻어오기 위해서 34번줄의 .getJSONObject(i)를 이용하고, 마지막으로 "1001", "1002" 등 String으로 표현된 id key의 값을 가져오기 위해 getString("id") 문법을 사용한다.

 

JSONArray의 길이는 .length(), Test 시 아래 코드에서의 볼드체와 같이 JSONException을 던져줘야 하고, try catch문으로 값을 표시해줘야 한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
@Test
    void jsonTest() throws JSONException {
        JSONObject jsonObject = new JSONObject("{\n" +
                "    \"id\": \"0001\",\n" +
                "    \"type\": \"donut\",\n" +
                "    \"name\": \"Cake\",\n" +
                "    \"ppu\": 0.55,\n" +
                "    \"batters\":\n" +
                "        {\n" +
                "            \"batter\":\n" +
                "                [\n" +
                "                    { \"id\": \"1001\", \"type\": \"Regular\" },\n" +
                "                    { \"id\": \"1002\", \"type\": \"Chocolate\" },\n" +
                "                    { \"id\": \"1003\", \"type\": \"Blueberry\" },\n" +
                "                    { \"id\": \"1004\", \"type\": \"Devil's Food\" }\n" +
                "                ]\n" +
                "        },\n" +
                "    \"topping\":\n" +
                "        [\n" +
                "            { \"id\": \"5001\", \"type\": \"None\" },\n" +
                "            { \"id\": \"5002\", \"type\": \"Glazed\" },\n" +
                "            { \"id\": \"5005\", \"type\": \"Sugar\" },\n" +
                "            { \"id\": \"5007\", \"type\": \"Powdered Sugar\" },\n" +
                "            { \"id\": \"5006\", \"type\": \"Chocolate with Sprinkles\" },\n" +
                "            { \"id\": \"5003\", \"type\": \"Chocolate\" },\n" +
                "            { \"id\": \"5004\", \"type\": \"Maple\" }\n" +
                "        ]\n" +
                "}");
        JSONObject batters = jsonObject.getJSONObject("batters");
        JSONArray batter = batters.getJSONArray("batter");
 
        IntStream.range(0, batter.length()).boxed().forEach(i -> {
            try {
                System.out.println(batter.getJSONObject(i).getString("id"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        });
    }
cs

 

 

 

 


 

 

참조

 

1) Adobe 오픈소스 - example 4

https://opensource.adobe.com/Spry/samples/data_region/JSONDataSetSample.html

728x90
반응형