使用 jackson 从 POJO 创建 JSON 架构时从 JSON 架构中删除"id"



如何从使用 Jackson 创建的 JSON 模式中删除 id 字段("id" : "urn:jsonschema:org:gradle:Person")

生成的架构

{
"type" : "object",
"id" : "urn:jsonschema:org:gradle:Person",
"properties" : {
"name" : {
"type" : "string"
}
}
}

POJO类(人.class)

import com.fasterxml.jackson.annotation.JsonProperty;
public class Person {
@JsonProperty("name")
private String name;
} 

使用 JSON 架构生成器

import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.module.jsonSchema.JsonSchema;
import com.fasterxml.jackson.module.jsonSchema.JsonSchemaGenerator;

public final class GetJsonSchema {
public static String getJsonSchema2(Class clazz) throws IOException {
ObjectMapper mapper = new ObjectMapper();
JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator(mapper);
JsonSchema jsonSchema = jsonSchemaGenerator.generateSchema(clazz);
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonSchema);
}
}

像这样调用

System.out.println(JsonSchema.Create(Person.class));

只需将 id 设置为null即可。 例如:

jsonSchema.setId(null);

正如Sachin所说,jsonSchema.setId(null)是实现目标的好方法。但Venkat是对的,复杂类型仍然具有id。

删除它们的一种方法是使用自定义SchemaFactoryWrapper,它将实例化自己的visitorContext拒绝提供URN。但是,请务必注意,如果一种类型引用自身(例如,可能具有子状态对象的状态对象),则此操作不起作用。

例如:

private static class IgnoreURNSchemaFactoryWrapper extends SchemaFactoryWrapper {
public IgnoreURNSchemaFactoryWrapper() {
this(null, new WrapperFactory());
}
public IgnoreURNSchemaFactoryWrapper(SerializerProvider p) {
this(p, new WrapperFactory());
}
protected IgnoreURNSchemaFactoryWrapper(WrapperFactory wrapperFactory) {
this(null, wrapperFactory);
}
public IgnoreURNSchemaFactoryWrapper(SerializerProvider p, WrapperFactory wrapperFactory) {
super(p, wrapperFactory);
visitorContext = new VisitorContext() {
public String javaTypeToUrn(JavaType jt) {
return null;
}
};
}
}
private static final String printSchema(Class c) {
try {
ObjectMapper mapper = new ObjectMapper();
IgnoreURNSchemaFactoryWrapper visitor = new IgnoreURNSchemaFactoryWrapper();
mapper.acceptJsonFormatVisitor(c, visitor);
JsonSchema schema = visitor.finalSchema();
schema.setId(null);
ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
String asString = writer.writeValueAsString(schema);
return asString;
} catch(Exception e) {
e.printStackTrace();
return null;
}
}

要删除复杂类型中的所有 id,您可以:

public static void removeId(JsonSchema schema) {
schema.setId(null);
if (JsonFormatTypes.OBJECT.equals(schema.getType())) {
schema.asObjectSchema().getProperties().forEach((key, value) -> removeId(value));
} else if (JsonFormatTypes.ARRAY.equals(schema.getType())) {
final ArraySchema.Items items = schema.asArraySchema().getItems();
if (items.isArrayItems()) {
Stream.of(items.asArrayItems().getJsonSchemas()).forEach(s -> removeId(s));
} else {
removeId(items.asSingleItems().getSchema());
}
}
}

PS:对象也可以具有其他属性。也许您需要删除他们的 ID。

最新更新