我使用Gson
将java对象序列化/反序列化为json。我想在UI
中显示它,并且需要一个模式来进行更好的描述。这将允许我编辑对象并添加比实际更多的数据
Gson
可以提供json架构吗?
是否有其他框架具有该功能?
答案 0 :(得分:25)
Gson库可能不包含任何类似的功能,但您可以尝试使用Jackson库和jackson-module-jsonSchema模块解决您的问题。例如,对于以下类:
class Entity {
private Long id;
private List<Profile> 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"
}
}
}
}
}
}
答案 1 :(得分:7)
查看JSONschema4-mapper项目。通过以下设置:
SchemaMapper schemaMapper = new SchemaMapper();
JSONObject jsonObject = schemaMapper.toJsonSchema4(Entity.class, true);
System.out.println(jsonObject.toString(4));
您将获得Michal Ziober answer to this question中提到的类的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"}
}
}