นี่เป็นการติดตามผลสำหรับคำถามนี้ สร้างคลาส DTO ขึ้นมาใหม่โดยไม่มีคุณสมบัติของฟิลด์ แทนที่จะกำหนดให้เป็นโมฆะโดยใช้ Gson/Jackson และ Spring Boot เดิมทีฉันโพสต์มันโดยพยายามทำให้มันใช้งานได้กับ Gson แต่สามารถทำได้กับ Jackson โดยใช้ @JsonInclude(JsonInclude.Include.NON_NULL)
เท่านั้น แต่ยังไม่สามารถหาสิ่งที่เทียบเท่ากับ Gson ได้ ดังนั้นฉันจึงสามารถเก็บสิ่งนั้นไว้เป็นห้องสมุดสำหรับโครงการได้
ลองใช้ @Expose(serialise=false, deserialise=false) โดยที่ฉันมีคำอธิบายประกอบ @JsonInclude หรือตั้งค่าฟิลด์นั้นเป็นโมฆะเนื่องจากคิดว่า 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;
}
}
หากใครมีแนวคิดอื่น ๆ เกี่ยวกับวิธีการทำเช่นนี้โปรด ขอบคุณมาก.