我Gson用来将java对象序列化/反序列化为json.我想要显示它UI,并需要一个模式来进行更好的描述.这将允许我编辑对象并添加比实际更多的数据.
可以Gson提供json架构吗?
是否有其他框架具有该功能?
Mic*_*ber 27
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
}
Run Code Online (Sandbox Code Playgroud)
这个程序:
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));
}
}
Run Code Online (Sandbox Code Playgroud)
下面的模式打印:
{
"type" : "object",
"properties" : {
"id" : {
"type" : "integer"
},
"profiles" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"name" : {
"type" : "string"
},
"value" : {
"type" : "string"
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 7
看看JSONschema4-mapper项目.通过以下设置:
SchemaMapper schemaMapper = new SchemaMapper();
JSONObject jsonObject = schemaMapper.toJsonSchema4(Entity.class, true);
System.out.println(jsonObject.toString(4));
Run Code Online (Sandbox Code Playgroud)
你会得到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"}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22472 次 |
| 最近记录: |