删除" id"使用jackson从POJO创建它时从JSON模式

时间:2016-12-13 05:17:06

标签: java json jackson

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

生成架构

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

对于POJO类(Person.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));

2 个答案:

答案 0 :(得分:1)

只需将ID设置为null即可。 E.g:

jsonSchema.setId(null);

答案 1 :(得分:0)

正如萨钦所说,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;
    }
}