从Java类创建JSON模式

我正在使用Gson将java对象序列化/反序列化为json。 我想在UI显示它,并需要一个模式来进行更好的描述。 这将允许我编辑对象并添加比实际更多的数据。
Gson可以提供json架构吗?
是否有其他框架具有该function?

Gson库可能不包含任何类似的function,但您可以尝试使用Jackson库和jackson-module-jsonSchema模块解决您的问题。 例如,对于以下类:

 class Entity { private Long id; private List profiles; // getters/setters } class Profile { private String name; private String value; // getters / setters } 

这个程序:

 import java.io.IOException; import java.util.List; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.module.jsonSchema.JsonSchema; import com.fasterxml.jackson.module.jsonSchema.factories.SchemaFactoryWrapper; public class JacksonProgram { public static void main(String[] args) throws IOException { ObjectMapper mapper = new ObjectMapper(); SchemaFactoryWrapper visitor = new SchemaFactoryWrapper(); mapper.acceptJsonFormatVisitor(Entity.class, visitor); JsonSchema schema = visitor.finalSchema(); System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema)); } } 

下面的模式打印:

 { "type" : "object", "properties" : { "id" : { "type" : "integer" }, "profiles" : { "type" : "array", "items" : { "type" : "object", "properties" : { "name" : { "type" : "string" }, "value" : { "type" : "string" } } } } } } 

看看JSONschema4-mapper项目。 通过以下设置:

 SchemaMapper schemaMapper = new SchemaMapper(); JSONObject jsonObject = schemaMapper.toJsonSchema4(Entity.class, true); System.out.println(jsonObject.toString(4)); 

你会得到Michal Ziober 对这个问题的答案中提到的类的JSON模式:

 { "$schema": "http://json-schema.org/draft-04/schema#", "additionalProperties": false, "type": "object", "definitions": { "Profile": { "additionalProperties": false, "type": "object", "properties": { "name": {"type": "string"}, "value": {"type": "string"} } }, "long": { "maximum": 9223372036854775807, "type": "integer", "minimum": -9223372036854775808 } }, "properties": { "profiles": { "type": "array", "items": {"$ref": "#/definitions/Profile"} }, "id": {"$ref": "#/definitions/long"} } }