Jackson @JsonInclude (JsonInclude.Include.NON_NULL)에 해당하는 Gson

Sep 28 2020

이것은 실제로이 질문에 대한 후속 조치입니다 .Gson / Jackson 및 Spring Boot를 사용하여 null을 갖는 대신 필드 속성없이 DTO 클래스를 다시 만듭니다 . 나는 원래 Gson과 함께 작동하도록 게시했지만 Jackson을 사용하여 만 할 수 있었지만 Gson을 사용하여 @JsonInclude(JsonInclude.Include.NON_NULL)이에 상응하는 것을 찾을 수 없으므로 프로젝트의 라이브러리로 유지할 수 있습니다.

@JsonInclude 주석이있는 @Expose (serialise = false, deserialise = false)를 사용하여 시도했거나 Gson이 기본적으로 무시할 것이라고 생각 했으므로 해당 필드를 null로 설정했지만 그렇게하지 않는 것 같습니다.

마지막으로 Gson이이를 무시하지만 작동하지 않는지 확인하기 위해 @Expose 주석을 완전히 제거하려고했습니다.

여기에 문제의 주요 부분을 붙여넣고 원본 게시물에 추가 된 추가 세부 정보를 유지합니다.

@Service
public class CategoryQueryServiceImpl implements CategoryQueryService {

@Autowired
private CategoryRepository categoryRepository;

@Autowired
private ReportRepository reportRepository;

ObjectMapper mapper = new ObjectMapper();

@Override
public CategoryQueryDto getCategory(UUID id) throws JsonProcessingException {

    if (categoryRepository.findById(id).isPresent()) {
        Category category = categoryRepository.findById(id).get();

        CategoryQueryDto categoryQueryDto = new CategoryQueryDto(category.getId(), category.getTitle());

          Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
          String converter = gson.toJson(categoryQueryDto);
          categoryQueryDto = gson.fromJson(converter, CategoryQueryDto.class);


        // Jackson
        //String converter = mapper.writeValueAsString(categoryQueryDto);

        //categoryQueryDto = mapper.readValue(converter, CategoryQueryDto.class);


        return categoryQueryDto;


    } else {
        return null;
    }

}


@AllArgsConstructor
@NoArgsConstructor
@Data
public class CategoryQueryDto {

@Expose()
private UUID id;
@Expose()
private String title;

// Jackson
// @JsonInclude(JsonInclude.Include.NON_NULL)
private List<ReportQueryDto> reports = null;

public CategoryQueryDto(UUID id, String title) {
    this.id = id;
    this.title = title;
}

}

누구든지 이것을 수행하는 방법에 대한 다른 아이디어가 있으면 제발. 대단히 감사합니다.

답변

1 anuragsaxena Sep 28 2020 at 16:43

null 필드를 직렬화하지 마십시오 (이것은 Gson 직렬화의 기본 동작입니다).

Employee employeeObj = new Employee(1, "John", "Smith", null);
                 
Gson gson = new GsonBuilder()
        .setPrettyPrinting()
        .create(); 
 
System.out.println(gson.toJson(employeeObj));

산출:

{
  "id": 1,
  "firstName": "John",
  "lastName": "Smith"
}

null 필드 직렬화 (JSON 출력에 null 값이 포함 된 사용자 지정 Gson 직렬화)

Employee employeeObj = new Employee(1, "John", "Smith", null);
                 
Gson gson = new GsonBuilder()
        .setPrettyPrinting()
        .serializeNulls()
        .create(); 
 
System.out.println(gson.toJson(employeeObj));

산출:

{
  "id": 1,
  "firstName": "John",
  "lastName": "Smith",
  "emailId": null
}
FrancislainyCampos Sep 29 2020 at 03:27

Spring Boot가 Jackson을 기본 직렬화 라이브러리로 사용하기 때문에 Gson의 기본 동작이 발생하지 않은 것 같습니다. application.properties파일 내에 아래 줄을 붙여 넣어 덮어 쓰면 문제가 해결되었습니다.

spring.mvc.converters.preferred-json-mapper=gson