Gson 相当于 Jackson @JsonInclude(JsonInclude.Include.NON_NULL)

Gson equivalent to Jackson @JsonInclude(JsonInclude.Include.NON_NULL)

这实际上是对这个问题 的跟进。我最初 post 编辑它试图让它与 Gson 一起工作,但只能使用 @JsonInclude(JsonInclude.Include.NON_NULL) 与 Jackson 一起做,但还没有找到 Gson 的等效项,所以我可以保留它作为项目的库。

尝试使用 @Expose(serialise=false, deserialise=false) 我有 @JsonInclude 注释或将该字段设置为 null 因为默认情况下 Gson 会忽略它,但它似乎没有这样做。

最后,我尝试完全删除 @Expose 注释,看看 Gson 是否会忽略它但也不起作用。

将问题的主要部分粘贴到此处,并保留添加到原始内容的额外详细信息 post。

@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;
}

}

如果有人对如何执行此操作有任何其他想法,请。 非常感谢。

不要序列化空字段(这是 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"
}

序列化空字段(JSON 输出中包含空值的自定义 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
}

Gson 的默认行为似乎没有发生,因为 SpringBoot 使用 Jackson 作为默认序列化库。通过在 application.properties 文件中粘贴以下行来覆盖它已解决我的问题。

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