프로그래밍/spring

JSON Array를 읽고 원하는 클래스로 변환하는 방법

승민아 2024. 3. 15. 17:46

API의 응답으로 위와 같이 JSON 데이터를 받는다.

나는 response -> body -> items -> item의 List를 받길 원한다.

JSON의 List는 어떻게 처리할 수 있을까?

 

테스트용으로 데이터의 contentid만 받아서 저장해보자.

 

다음과 같이 클래스를 만든다.

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class LocationId {
    private String contentid;
}
  • JsonIgnoreProperties(ignoreUnknow) : item 리스트의 원소 데이터에 contentid 외에도 많은 필드들이 있다. 만약 내가 원하는 필드만 바인딩하길 원한다면 이 옵션을 주면 된다. 이 옵션을 쓰지 않는다면 모든 필드를 바인딩하도록 필드를 작성해야한다.

 

 

String response = restTemplate.getForObject(fullUrl, String.class);

JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray= jsonObject.getJSONObject("response").getJSONObject("body").getJSONObject("items").getJSONArray("item");

ObjectMapper objectMapper = new ObjectMapper();
for (Object o : jsonArray) {
    LocationId locationId = objectMapper.readValue(o.toString(), LocationId.class);
    System.out.println("locationId = " + locationId);
}

JSONObject를 통해 오브젝트 단위를 타고 들어간다.

응답으로 받은 JSON의 item 부분은 배열 부분이다.

getJSONArray를 통해 추출하자. 그리고 JsonArray의 인스턴스를 반복문을 돌며 Object로 받자.

objectMapper를 통해 클래스로 바인딩할 수 있다.

 

바인딩 결과