Notice
Recent Posts
Recent Comments
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- Python
- 게임
- 클리어
- 구글
- game
- MySQL
- 아이폰
- 설치
- 닌텐도스위치
- 인그레스
- 쿠팡
- OSX
- 요리
- 카카오
- IntelliJ
- 판교
- 맥북
- PERL
- Mac
- Java
- 공략
- arduino
- 유튜브
- 프렌즈런
- 맛집
- Linux
- Installation
- Ingress
- 이마트트레이더스
- Today
- 2,212
- Total
- 3,575,789
준호씨의 블로그
Jackson Json - null 필드 생략하기 본문
반응형
@Data
@Builder
public class Person {
private String firstName;
private String lastName;
private String byName;
private String phoneNumber;
}
클래스가 있고 (편의상 lombok을 사용합니다.)
Person person = Person.builder()
.firstName("Michael")
.lastName("Jordan")
.byName("Air Jordan")
.build();
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(person));
(예쁘게 출력하기 위해 writerWithDefaultPrettyPrinter를 사용했고 평소에는 writerWithDefaultPrettyPrinter는 생략하고 mapper.writeValueAsString만 사용하면 됩니다.)
person 인스턴스를 생성하고 json 문자로 변경하면
{
"firstName" : "Michael",
"lastName" : "Jordan",
"byName" : "Air Jordan",
"phoneNumber" : null
}
처럼 나옵니다.
그런데 null이 있는 경우 null을 생략하고 싶을 때가 있습니다. API 서버를 개발할 때 응답 결과 데이터를 위한 class는 하나만 만들어 사용하는데 상태에 따라 항목이 달라지는 경우가 있을 때 null이냐 아니냐에 따라 항목을 숨기거나 보여주도록 처리할 수 있습니다.
아래처럼 @JsonInclude(JsonInclude.Include.NON_NULL)
을 추가해 주면 null인 데이터는 json결과에 나타나지 않습니다.
@Data
@Builder
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Person {
private String firstName;
private String lastName;
private String byName;
private String phoneNumber;
}
결과
{
"firstName" : "Michael",
"lastName" : "Jordan",
"byName" : "Air Jordan"
}
애노테이션을 필드마다 따로 지정해 줄 수도 있습니다.
@Data
@Builder
public class Person {
private String firstName;
private String lastName;
private String byName;
@JsonInclude(JsonInclude.Include.NON_NULL)
private String phoneNumber;
}
애노테이션을 사용하지 않고 mapper 설정을 사용할 수도 있습니다.
mapper.setSerializationInclusion(Include.NON_NULL);
참고로 jackson 2.5 이하 구 버전에서는
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
또는
mapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);
을 사용합니다.
spring boot 프로젝트인 경우 application.properties 에서 설정할 수 있습니다.
spring.jackson.default-property-inclusion=non_null
application.yaml 파일로 설정하는 경우
spring:
jackson:
default-property-inclusion: non_null
처럼 설정할 수 있습니다.
반응형
'개발이야기' 카테고리의 다른 글
Jackson Json - json name을 snake case로 바꾸기 (0) | 2020.08.01 |
---|---|
Jackson Json - json 가독성 높이기. pretty printer (0) | 2020.07.31 |
OSX - npm오류. gyp: No Xcode or CLT version detected! (0) | 2020.07.29 |
IntelliJ - Add File to Git 끄기 (0) | 2020.07.23 |
Spring Boot - spring initializr 에서 프로젝트 생성하기. https://start.spring.io (0) | 2020.07.20 |
- Tag
- Jackson, JSON, JsonInclude, NON_NULL, NULL, null생략, SpringBoot
2 Comments