JAVA/Spring

Spring Json List에 값이 안들어가는 오류 해결 방법

bestinu 2022. 2. 23. 06:52
728x90

게시판의 게시글을 가져오는 api를 작업하고 있는데, 작업이 끝난 후에 Postman으로 확인을 해보면 리스트 안의 내용이 텅텅 비어있는 문제가 생겼다.

에러가 뜨는 것도 아니라서 우선 Serivce에서 Mapper로 DB의 게시글 목록 잘 가져오는 것 확인하고, 문제가 없길래 DTO에 값이 잘 안들어가나 하고 Controller에서 리턴해줄 때 body 값을 확인했는데 body에도 값이 정상적으로 다 들어가 있길래 정말 당황스러웠다.

 

그래서 온갖 검색어로 다 찾아보면서 삽질하고 있었는데, 겨우겨우 stackoverflow에서 답을 찾을 수 있었다.

해당 질문 링크

 

Spring REST Controller returns empty JSON. Iterable data structure. Why?

I realize a very similar question was asked and closed because it wasn't specific enough and didn't specify outcomes. Closed Off Topic Problem: JSON being returned from REST controller is empty.

stackoverflow.com

 

문제는 Controller에서 body로 넣어주는 ResponseDto에 Getter가 없어서였다...

@JsonInclude(JsonInclude.Include.NON_NULL)
@AllArgsConstructor
@Getter // <- 이게 없어서 빈 Json 값으로 나왔던 것
@Builder
public class PostResponse {
    private String content;
    private String title;
    private String writer;
    private LocalDateTime writeDate;

    public static PostResponse of(Post post) {
        return PostResponse.builder()
                .content(post.getContent())
                .title(post.getTitle())
                .writer(post.getWriter())
                .writeDate(post.getWriteDate())
                .build();
    }
}

List를 반환해주는 방법이 잘못된 줄 알고 한참 다른 사람들 코드도 비교해가면서 거의 세시간 넘게 찾아다녔는데

뜬금없이 @Getter 어노테이션을 안붙여줘서 문제가 생겼다는걸 확인하고 수정하니 바로 정상적으로 작동했다.

 

첫 Spring으로 만드는 프로젝트라 그런지 이런 기본적인 것도 모르는 상태로 개발하고 있었는데 그래도 이렇게 하나하나 배워가니 더 열심히 해야겠다. 

 

728x90