我正在将jackson-databind从版本2.9.0升级到2.9.8,并且遇到一个问题,其中@JsonProperty
值导致spring将来自父方法的@JsonSerialize
值映射到相同的名字。
子类的示例:
public class SubClassEntity extends AbstractEntity {
@JsonView(SubClassEntity.class)
@JsonProperty("user")
@JsonSerialize(using = UserSubClassEntitySerialzer.class)
public Entity getSubClassUser() {
return super.getEntity();
}
@JsonView(SubClassEntity.class)
@JsonProperty("userAlternative")
public UserEntity getSubClassUserAlternative() {
final User user = super.getUserAlternative();
return null != user ? new UserEntity(user) : null;
}
}
父类的示例
public class AbstractEntity {
protected final Entity entity;
public AbstractEntity (final Entity entity) {
this.entity = entity;
}
public Entity getEntity() {
return this.entity;
}
@JsonView(Object.class)
@JsonSerialize(using = UserInfoSerializer.class)
public User getUser() {
return this.entity.getUser();
}
@JsonView(Object.class)
@JsonSerialize(using = UserInfoSerializer.class)
public User getUserAlternative() {
return this.entity.getUserAlternative();
}
}
UserSubClassEntitySerialzer
public class UserSubClassEntitySerialzer extends JsonSerializer<Entity> {
does stuff
}
UserInfoSerializer
public class UserInfoSerializer extends JsonSerializer<User> {
does stuff
}
当我们尝试序列化子类时,无论是否在子类中设置了一个名称,都会使用在JsonProperty中找到的名称的父类上设置的JsonSerializer。这会导致ClassCastException:
com.fasterxml.jackson.databind.JsonMappingException: package.UserEntity cannot be cast to package.User(through reference chain: package.SubClassEntity["userAlternative"])
和
com.fasterxml.jackson.databind.JsonMappingException: package.Entity cannot be cast to package.User(through reference chain: package.SubClassEntity["user"])
at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:394)
at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:353)
at com.fasterxml.jackson.databind.ser.std.StdSerializer.wrapAndThrow(StdSerializer.java:316)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:727)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155)
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider._serialize(DefaultSerializerProvider.java:480)
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:319)
at com.fasterxml.jackson.databind.ObjectWriter$Prefetch.serialize(ObjectWriter.java:1396)
at com.fasterxml.jackson.databind.ObjectWriter._configAndWriteValue(ObjectWriter.java:1120)
at com.fasterxml.jackson.databind.ObjectWriter.writeValueAsString(ObjectWriter.java:993)
在确定序列化程序时,子类是否可以忽略JsonProperty值?