当它具有conrete实现依赖该请求的另一个属性的抽象属性时,如何从JSON(使用Jackson(正确地对象进行正确的对象?
这可能是一个示例中最好的描述。
我的休息端点的请求主体包括一个属性,该属性是一个抽象类型,具有多个具体实现,应根据discriminator
属性进行审理:
@Getter
@Builder
@AllArgsConstructor
public class SomeRequestBody {
@NotNull
@NotBlank
@NumberFormat
private final String discriminator;
@NotNull
private final SomeAbstractClass someAbstractClass;
}
有问题的抽象类
@Getter
@AllArgsConstructor
public abstract class SomeAbstractClass{
@NotNull
@NotBlank
protected final String commonProperty;
}
示例抽象类的实现
@Getter
public class ConcreteImplementationA extends SomeAbstractClass {
@Builder
@JsonCreator
public ConcreteImplementationA(
@NotNull @NotBlank @JsonProperty("commonProperty") String commonProperty,
@NotNull @NotBlank @JsonProperty("specificProperty") Date specificProperty) {
super(commonProperty);
this.specificProperty = specificProperty;
}
@NotNull
@NotBlank
private final String specificProperty;
}
我尝试的...
@Getter
@Builder
@AllArgsConstructor
public class SomeRequestBody {
@NotNull
@NotBlank
@NumberFormat
private final String discriminator;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY, property = "discriminator")
@JsonSubTypes({
@JsonSubTypes.Type(value = ConcreteImplementationA.class, name = "1"),
Other implementations...)
})
@NotNull
private final SomeAbstractClass someAbstractClass;
}
但是,我得到以下例外:
"Type definition error: [simple type, class abc.SomeRequestBody]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `abc.SomeRequestBody`, problem: Internal error: no creator index for property 'someAbstractClass' (of type com.fasterxml.jackson.databind.deser.impl.FieldProperty)n at [Source: (PushbackInputStream); line: 8, column: 1]"
实现我需要的正确方法是什么?
事实证明,该抽象属性的绝对化不是问题,而是不可变的属性,而龙目族的@AllArgsConstructor
与杰克逊的效果不佳。我创建了一个@jsoncreator注释的构造函数,而不是使用注释,现在可以正常工作。