본문 바로가기
spring | spring boot

JSON object, array parsing

by socialcomputer 2022. 2. 15.
반응형

response body가 거의 json으로 와서 필요한 정보들만 가져오고 싶어 찾아봤더니 JSONObject 와 JSONAarray라는 것이 있었다. 

 

내가 사용한 예

JSONObject jsonObject = new JSONObject(responseEntity.getBody());
JSONArray items = jsonObject.getJSONArray("items");
JSONObject item = items.getJSONObject(0);
user.setChannelId(item.getString("id"));
user.setTitle(item.getJSONObject("snippet").getString("title"));

JSONObject로 전체를 받아온 후, items이름가진 배열을 JSONArray로 받아오기.

그중 나는 맨 처음 것만 item(JSONObject)로 가져와서 id속성명 값을 받고, 

item아래의 snippet이름의 객체를 찾아 title속성명 값을 받아왔다. 

 

유튜브 api에서 받아온 channel List response 의 구조

{
  "kind": "youtube#channelListResponse",
  "etag": "fjskdfjeifjwfewfw",
  "pageInfo": {
    "totalResults": 1,
    "resultsPerPage": 5
  },
  "items": [
    {
      "kind": "youtube#channel",
      "etag": "dsffwgwegwggt",
      "id": "채널아이디",
      "snippet": {
        "title": "채널명",
        "description": "",
        "publishedAt": "채널 생성 날짜",
        "thumbnails": {
          "default": {
            "url": "http://fkdfiwefj.dfkd.fdkf/dfd/dfdf/sdfdsfsdgb.dfmdk",
            "width": 88,
            "height": 88
          },
          "medium": {
            "url": "https://yt3.ggpht.com/dsfjsdklfjsdlkfjlsdfjlskdjfsd/fdsjfdjfsdf",
            "width": 240,
            "height": 240
          },
          "high": {
            "url": "https://yt3.ggpht.com/fdsfnwsefjwejf/fewhfwehfhrg/fsd-fdsf",
            "width": 800,
            "height": 800
          }
        },
        "localized": {
          "title": "채널 이름",
          "description": ""
        }
      }
    }, // item[0]
    {
      "kind": "youtube#channel",
      "etag": "dsffwgwegwggt",
      "id": "채널아이디",
      "snippet": {
        "title": "채널명",
        "description": "",
        "publishedAt": "채널 생성 날짜",
        "thumbnails": {
          "default": {
            "url": "http://fkdfiwefj.dfkd.fdkf/dfd/dfdf/sdfdsfsdgb.dfmdk",
            "width": 88,
            "height": 88
          },
          "medium": {
            "url": "https://yt3.ggpht.com/dsfjsdklfjsdlkfjlsdfjlskdjfsd/fdsjfdjfsdf",
            "width": 240,
            "height": 240
          },
          "high": {
            "url": "https://yt3.ggpht.com/fdsfnwsefjwejf/fewhfwehfhrg/fsd-fdsf",
            "width": 800,
            "height": 800
          }
        },
        "localized": {
          "title": "채널 이름",
          "description": ""
        }
      }
    }// item[1]
  ]
}

 

 

 

 

반응형

댓글