Java 将值对象用作实体id时自定义序列化
我想在实体中使用值对象作为数据库id。我还想要干净的JSON。假设我有这个实体:Java 将值对象用作实体id时自定义序列化,java,json,serialization,Java,Json,Serialization,我想在实体中使用值对象作为数据库id。我还想要干净的JSON。假设我有这个实体: private static class TestEntity { private TestEntityId id; private String mutableProperty; public TestEntity(TestEntityId id) { this.id = id; } public TestEntityId getId() {
private static class TestEntity {
private TestEntityId id;
private String mutableProperty;
public TestEntity(TestEntityId id) {
this.id = id;
}
public TestEntityId getId() {
return id;
}
public String getMutableProperty() {
return mutableProperty;
}
public void setMutableProperty(String mutableProperty) {
this.mutableProperty = mutableProperty;
}
}
具有此id类的:
private static class TestEntityId extends ImmutableEntityId<Long> {
public TestEntityId(Long id) {
super(id);
}
}
但我想得到这个:
{"id":{"id":1},"mutableProperty":"blabla"}
{"id":1,"mutableProperty":"blabla"}
通过添加自定义序列化程序,我成功地使序列化正常:
addSerializer(ImmutableEntityId.class, new JsonSerializer<ImmutableEntityId>() {
@Override
public void serialize(ImmutableEntityId immutableEntityId, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
jsonGenerator.writeNumber( (Long)immutableEntityId.getId() );
}
});
addSerializer(ImmutableEntityId.class,新的JsonSerializer(){
@凌驾
public void serialize(ImmutableEntityId ImmutableEntityId,JsonGenerator JsonGenerator,SerializerProvider SerializerProvider)引发IOException,JsonProcessingException{
jsonGenerator.WriteEnumber((长)immutableEntityId.getId());
}
});
(我知道演员阵容不是很好,但就问题而言,请忽略这一点)
问题是如何为它编写反序列化程序?不知何故,Jackson应该跟踪在反序列化
TestEntity
时,他需要创建一个TestEntityId
实例(而不是ImmutableEntityId
超类)。我可以为每个实体编写序列化程序和反序列化程序,但我希望有一个更通用的解决方案。使用。它也可以完美地处理具有单个属性的对象,IIRC。一般来说,建议是可以的,但是如果在DTO上使用@jsonUnrapped,使用带有Webflux的Spring Boot,则会出现错误415。