๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๊ฐœ๋ฐœ/JAVA

[JAVA] jackson -JsonInclude ์†์„ฑ (null, empty๋“ฑ์˜ ๋ฐ์ดํ„ฐ ์ œ์™ธํ•˜๊ธฐ)

by ynzu๐Ÿค 2022. 3. 11.
๋ฐ˜์‘ํ˜•

 

VO๊ฐ์ฒด๋ฅผ JSON์œผ๋กœ ๋ณ€ํ™˜ํ•  ๋•Œ ํฌํ•จ๋˜๋ฉด ์•ˆ๋˜๋Š” ๋ณ€์ˆ˜์— @JsonIgnore ์–ด๋…ธํ…Œ์ด์…˜์„ ์„ ์–ธํ•˜์—ฌ JSON์— ํฌํ•จ๋˜์ง€ ์•Š๋„๋ก ํ•  ์ˆ˜ ์žˆ๋‹ค.

ํ•˜์ง€๋งŒ ์ƒํ™ฉ์— ๋”ฐ๋ผ json ํฌํ•จ ์—ฌ๋ถ€๊ฐ€ ๋‹ฌ๋ผ์ง€๋Š” ๊ฒฝ์šฐ ์•„๋ž˜์™€ ๊ฐ™์€ ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค.

ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); //null์ธ ๋ฐ์ดํ„ฐ๋ฅผ ์ œ์™ธํ•˜๊ณ  json ์ƒ์„ฑ
mapper.writeValueAsString(testVO);

VO์— default๋กœ ์ ์šฉํ•˜๋ ค๋ฉด VO Class์— @JsonInclude ์–ด๋…ธํ…Œ์ด์…˜์„ ์„ ์–ธํ•˜๋ฉด ๋œ๋‹ค.

@JsonInclude(JsonInclude.Include.NON_NULL)

 

1. JsonInclude.Include.ALWAYS

  • ๋ชจ๋“  ๋ฐ์ดํ„ฐ๋ฅผ JSON์œผ๋กœ ๋ณ€ํ™˜ํ•œ๋‹ค.

 

2. JsonInclude.Include.NON_NULL

  • null์ธ ๋ฐ์ดํ„ฐ๋Š” ์ œ์™ธํ•œ๋‹ค.

 

3. JsonInclude.Include.NON_ABSENT

  • null์ธ ๋ฐ์ดํ„ฐ์™€
  • ์ฐธ์กฐ ์œ ํ˜• (Java 8 'Optional'๋˜๋Š” {link java.utl.concurrent.atomic.AtomicReference})์˜ "absent"๊ฐ’์€ ์ œ์™ธํ•œ๋‹ค.
์˜ˆ๋ฅผ ๋“ค์–ด TestVO์— private AtomicReference<String> ar; ๊ฐ€ ์„ ์–ธ๋˜์–ด ์žˆ๊ณ ,
testVO.setAr(new AtomicReference<String>()); ๋งŒ ํ–ˆ์„ ๊ฒฝ์šฐ ์ œ์™ธ๋œ๋‹ค. 

 

4. JsonInclude.Include.NON_EMPTY

  • null์ธ ๋ฐ์ดํ„ฐ์™€
  • absent ๋ฐ์ดํ„ฐ์™€
  • Collections, Map์˜ isEmpty()๊ฐ€ true์ธ ๋ฐ์ดํ„ฐ์™€
  • Array์˜ length๊ฐ€ 0์ธ ๋ฐ์ดํ„ฐ์™€
  • String์˜ length๊ฐ€ 0์ธ ๋ฐ์ดํ„ฐ๋Š” ์ œ์™ธํ•œ๋‹ค.

 

5. JsonInclude.Include.NON_DEFAULT

  • empty์ธ ๋ฐ์ดํ„ฐ์™€
  • ๊ธฐ๋ณธํ˜• ํƒ€์ž…์ด default๊ฐ’์ธ ๋ฐ์ดํ„ฐ์™€ (์˜ˆ: int/Intege=0, boolean=true)
  • Date์˜ timestamp๊ฐ€ 0L์ธ ๋ฐ์ดํ„ฐ๋Š” ์ œ์™ธํ•œ๋‹ค.

 

 

728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€