@JsonTypeInfo与Spring Data Rest一起使用会导致序列化错误

4
我目前正在尝试使用 EclipseLinkspring-data-jpaspring-data-rest 进行一种情境测试,其中我有一个带有继承的 Embeddable 类。
这个情境相当简单:一个 Parent 包含一个值,可以是 PercentageValueAbsoluteValue
映射: Parent 持有一个可嵌入的值:
@Entity
public class Parent {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Embedded
    private Value value;
}

Value 是不同值的抽象超类

@Embeddable
@Customizer(Customizers.ValueCustomizer.class)
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="type")
@JsonSubTypes({
        @Type(name="PERCENTAGE", value=PercentageValue.class),
        @Type(name="ABSOLUTE", value=AbsoluteValue.class)})
public abstract class Value {}

PercentageValue 是一个具体的值实现的示例。

@Embeddable
@Customizer(Customizers.PercentageValueCustomizer.class)
@JsonSerialize(as = PercentageValue.class)
public class PercentageValue extends Value {
    private BigDecimal percentageValue;
}

使用 EclipseLink 自定义程序,我可以让嵌入式继承工作,但是 Spring Data REST 似乎无法序列化值对象,因为缺少类型信息。
对父资源的 GET 请求会导致以下异常:
``` .w.s.m.s.DefaultHandlerExceptionResolver : Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: Type id handling not implemented for type java.lang.Object (by serializer of type org.springframework.data.rest.webmvc.json.PersistentEntityJackson2Module$NestedEntitySerializer) (through reference chain: org.springframework.data.rest.webmvc.json.["content"]->com.example.Parent["value"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Type id handling not implemented for type java.lang.Object (by serializer of type org.springframework.data.rest.webmvc.json.PersistentEntityJackson2Module$NestedEntitySerializer) (through reference chain: org.springframework.data.rest.webmvc.json.["content"]->com.example.Parent["value"]) ```
看起来 NestedEntitySerializer 没有实现 com.fasterxml.jackson.databind.JsonSerializer#serializeWithType,而是回退到只抛出异常的标准实现。
如果我移除 @JsonTypeInfo 注解,序列化可以正常工作,但是当然 POST 会失败,因为 Jackson 缺少类型信息以进行适当的反序列化。
对此有何想法?有没有办法让带有 JsonTypeInfo 的序列化工作?
完整项目可在 GitHub 上获取。

相同的问题在普通实体场景中也会出现:https://github.com/mduesterhoeft/spring-data-rest-entity-inheritance https://jira.spring.io/browse/DATAREST-872 - Mathias Dpunkt
1
目前已经修正了这个问题,并且至少在使用@JsonTypeInfo以及include=JsonTypeInfo.As.EXISTING_PROPERTY的情况下能够正常工作。 - Mathias Dpunkt
1个回答

0

当涉及将数据序列化到REST输出时,Spring Data REST存在许多已记录的限制,以支持Jackson的@JsonTypeInfo

目前,似乎@JsonTypeInfo(include=JsonTypeInfo.As.EXISTING_PROPERTY)可以正常工作(spring-data-rest#1242),但其他JsonTypeInfo.As类型则不行(spring-data-rest#1269)。

您应该可以将您的模型迁移到使用JsonTypeInfo.As.EXISTING_PROPERTY而不是JsonTypeInfo.As.PROPERTY


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接