我正在使用 openapi 生成器来生成我的类
基础类
@JsonPropertyOrder({
EntityType.CONTAINER
})
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "...")
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "structure_type", visible = true)
@JsonSubTypes({
@JsonSubTypes.Type(value = SonClass1, name = "sonClass1"),
@JsonSubTypes.Type(value = SonClass2, name = "sonClass2"),
})
public class MyBaseClass {
public static final String JSON_PROPERTY_CONTAINER = "container";
private String container;
}
SonClass1 示例
@JsonPropertyOrder({
NodeType.JSON_PROPERTY_PROPERTIES,
})
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "...")
public class SonClass1 extends MyBaseClass {
public static final String JSON_PROPERTY_PROPERTIES = "properties";
private Map<String, Property> properties = null;
}
我正在尝试使用 Mapper.readValue(); 使用 ObjectMapper 构建对象 结果异常:
com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Could not resolve subtype of [simple type, class com.MySon1]: missing type id property 'structure_type'
您能解释一下这是为什么吗?我能用它做什么?这是否意味着我必须在每个子类上添加属性“structure_type”?
Openapi yaml 看起来像这样
MyBaseClass:
type: object
properties:
container:
type: string
discriminator:
propertyName: structure_type
mapping:
sonClass: '#/sonClass1'
sonClass1:
allOf:
- $ref: '#/MyBaseClass'
- type: object
properties:
properties:
type: object
additionalProperties:
$ref: '#/Property'
我的基类应该有“structure_type”属性,添加此属性后 - 一切正常。
在我的例子中,json字符串与JAVA对象类型不匹配。我更正了我的 json 字符串,
我已通过更正 JSON 格式解决了此异常。如果类中有多个对象的数组,则 JSON 格式也应该嵌套。查看此链接以使用正确的 JSON 格式如何格式化 JSON:对象数组或包含对象元素的文档?