【发布时间】:2021-01-14 06:14:10
【问题描述】:
这实际上是对这个问题Recreate DTO class without field property instead of having it null using Gson/Jackson and Spring Boot 的跟进。我最初发布它是为了让它与 Gson 一起使用,但只能使用 @JsonInclude(JsonInclude.Include.NON_NULL) 与 Jackson 一起使用,但无法找到与 Gson 对应的等效项,因此我可以将其保留为项目的库。
尝试使用 @Expose(serialise=false, deserialise=false) 我有 @JsonInclude 注释或将该字段设置为 null 因为默认情况下 Gson 会忽略它,但它似乎没有这样做。
最后,我尝试完全删除 @Expose 注释,看看 Gson 是否会忽略它但也不起作用。
在此处粘贴问题的主要部分,并保留添加到原始帖子中的额外细节。
@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;
}
}
如果有人对如何做到这一点有任何其他想法,请。 非常感谢。
【问题讨论】:
标签: java spring-boot serialization jackson gson