TIL

[Spring] @JsonInclude(JsonInclude.Include.NON_NULL)

우성팔 2023. 12. 22.

제목, 작성자명(nickname), 작성 날짜를 조회하기

PostResponseDto에는 여러가지 필드들이 있지만 위의 3가지만 출력을 해보기로 하였다

 

PostResponseDto

@Getter
@NoArgsConstructor
@AllArgsConstructor
public class PostResponseDto {
    private Long id;
    private String nickName;

    @JsonFormat(pattern = "yyyy-MM-dd")
    private LocalDateTime createdAt;
    @JsonFormat(pattern = "yyyy-MM-dd")
    private LocalDateTime modifiedAt;

    private String title;
    private String content;
    private List<CommentResponseDto> comments;

    public PostResponseDto(Post post) {
        this.id = post.getId();
        this.title = post.getTitle();
        this.content = post.getContent();
        this.nickName = post.getUser().getNickname();
        this.createdAt = post.getCreatedAt();
        this.modifiedAt = post.getModifiedAt();
        this.comments = post.getComments()
                .stream()
                .map(CommentResponseDto::new)
                .collect(Collectors.toList());
    }

    public PostResponseDto(String nickName, LocalDateTime createdAt,String title) {
        this.nickName = nickName;
        this.createdAt = createdAt;
        this.title = title;
    }

}

 

일단 PostResponseDto를 만들어주고 제목, 작성자명, 작성날짜를 매개변수로 하는 생성자를 만들어줌

 

포스트맨을 이용해서 결과 확인

[Spring] @JsonInclude(JsonInclude.Include.NON_NULL) - undefined - undefined - 포스트맨을 이용해서 결과 확인

원하는 작성자, 작성일, 제목을 불러왔지만 나머지 필드들도 null값으로 같이 나오면서 

지저분한 결과가 출력된 것을 볼 수 있음

 

 

@JsonInclude(JsonInclude.Include.NON_NULL)

@Getter
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL) // 추가
public class PostResponseDto {
    private Long id;
    private String nickName;

    @JsonFormat(pattern = "yyyy-MM-dd")
    private LocalDateTime createdAt;
    @JsonFormat(pattern = "yyyy-MM-dd")
    private LocalDateTime modifiedAt;

    private String title;
    private String content;
    private List<CommentResponseDto> comments;

    public PostResponseDto(Post post) {
        this.id = post.getId();
        this.title = post.getTitle();
        this.content = post.getContent();
        this.nickName = post.getUser().getNickname();
        this.createdAt = post.getCreatedAt();
        this.modifiedAt = post.getModifiedAt();
        this.comments = post.getComments()
                .stream()
                .map(CommentResponseDto::new)
                .collect(Collectors.toList());
    }

    public PostResponseDto(String nickName, LocalDateTime createdAt,String title) {
        this.nickName = nickName;
        this.createdAt = createdAt;
        this.title = title;
    }

}

 

@JsonInclude(JsonInclude.Include.NON_NULL)을 PostResponseDto에 추가해줌

 

[Spring] @JsonInclude(JsonInclude.Include.NON_NULL) - undefined - undefined - @JsonInclude(JsonInclude.Include.NON_NULL)

null값로 이루어진 필드들이 전부 사라지고 내가 원하는 필드들만 출력이 되는 것을 볼 수 있음

 

댓글