웹 개발

[spring] Json return 시, null 항목 제거하는 방법

노루아부지 2022. 2. 13. 19:01

Spring에서는 @ResponseBody를 통해 DTO, VO, Map 등을 리턴하면 JSON형태로 변환됩니다.

그 과정에서 특정 키에 null이 있어도 key: null과 같이 리턴이 됩니다.

 

아래와 같은 코드가 있다고 가정해 봅시다.

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class UserDto {
  private int code;
  private String id;
  private String name;
  private int age;
}
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
  @RequestMapping("/getUserInfo")
  public UserDto getUserInfo() {
    UserDto dto = new UserDto();
    dto.setId("admin");

    return dto;
  }
}

 

이 코드를 실행한 후 http://localhost:8080/getUserInfo를 호출하면 다음과 같이 리턴됩니다.

{
    "code"0,
    "id""admin",
    "name"null,
    "age"0
}

 

이와 같이 name에는 아무 값도 넣지 않았기 때문에 "name": null로 리턴이 된 것을 확인할 수 있습니다.

 

 

[참고]

@RestController를 사용하면 컨트롤러에 @ResponseBody가 포함되어 있어서 예제에서는 명시하지 않았습니다.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
  /**
   * The value may indicate a suggestion for a logical component name,
   * to be turned into a Spring bean in case of an autodetected component.
   * @return the suggested component name, if any (or empty String otherwise)
   * @since 4.0.1
   */
  @AliasFor(annotation = Controller.class)
  String value() default "";
}

 

 

 

다시 돌아와서, "name": null과 같이 null인 항목 자체를 삭제하려면 다음과 같이 DTO에 @JsonInclude(Include.NON_NULL) 를 사용하면 됩니다.

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@JsonInclude(JsonInclude.Include.NON_NULL)
public class UserDto {
  private int code;
  private String id;
  private String name;
  private int age;
}

 

다시 URL을 호출하면 다음과 같이 null인 항목의 key 자체가 사라진 것을 확인할 수 있습니다.

{
    "code"0,
    "id""admin",
    "age"0
}
728x90
loading