개요
Json데이터를 파싱할 때 Java에서는 JsonNode를 많이 사용한다. 또한 비즈니스 로직에서 이를 편하게 사용하기 위해 사전 정의한 Dto객체로 변환할 필요가 존재한다.
메인
아래는 RestClient를 통해 받은 Json데이터를 처리하는 코드이다.
// 인기 검색어 쿼리
try {
Request request = new Request("GET", "/search_history/_search");
request.setJsonEntity(queryJson);
Response response = restClient.performRequest(request);
String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
JsonNode root = objectMapper.readTree(responseBody);
JsonNode topKeywords = root.path("aggregations")
.path("recent_popular_keywords")
.path("value")
.path("topKeywords");
log.info("파싱 부분: {}", topKeywords);
searchPopularResponses = objectMapper.readValue(topKeywords.toString(), new TypeReference<List<SearchPopularResponse>>() {});
} catch (IOException e) {
throw new ApiException(SchedulerError.SERVER_ERROR, "서버 스케줄러 인기 검색어 오류");
}
먼저 ObjectMapper를 통해 문자열 Json데이터를 Tree 구조로 만들어준다.
그리고 path메서드를 통해 추출할 노드까지 내려가준다.
ObjectMapper를 통해 node 데이터를 dto로 파싱하는 방법은 대표적으로 두가지가 있다.
- treeToValue 메서드
- readValue 메서드
먼저 첫번째 방법이다.
간단하게 JsonNode를 바로 Dto객체로 변환하는 과정이다.
데이터 구조가 단순한 경우(단일 데이터)에 쉽게 파싱할 수 있다.
하지만 데이터 구조가 배열인 경우에는 파싱이 불가능하다.
objectMapper.treeToValue(topKeywords, Dto.class)
두번째 방법이다.
readValue를 통해 문자열 데이터를 원하는 형태로 변환하는 과정이다.
TypeReference를 통해 타입을 지정하는데, TypeReference는 추상 클래스이기 때문에 직접 생성할 수 없다. 따라서 내부적으로 익명 클래스를 만들어주기 위해 {}을 추가해야 한다.
추상 클래스이지만, 추상 메서드가 존재하지 않기 때문에, 내부적으로 구현하지 않아도 에러가 발생하지 않는다.
objectMapper.readValue(
topKeywords.toString(),
new TypeReference<List<SearchPopularResponse>>() {}
);
'Springboot' 카테고리의 다른 글
[Spring Boot] 에러 로그를 이메일로 자동 전송하기 – SMTP + Logback 연동 (0) | 2025.03.23 |
---|---|
[Spring + Redis] 비밀번호 설정 및 Lettuce 연결 설정 정리 (0) | 2025.03.21 |
[SpringSecurity] BCrypt 비밀번호 인증 구현 (0) | 2025.03.12 |
[SpringBoot] Filter에서의 예외처리 (0) | 2025.03.08 |
[스프링 부트] Stream.map() 함수 (0) | 2024.07.20 |