从Java类创建JSON模式 [英] Create JSON schema from Java class
问题描述
我使用 Gson
来将java对象序列化/反序列化为json。我想将它显示在 UI
中,并且需要一个模式来更好地描述。这将允许我编辑对象并添加比实际数据更多的数据。
可以 Gson
提供json模式?
任何其他框架都有这种功能?
Gson库可能不包含任何此类功能,但您可以尝试解决您的问题与 Jackson 图书馆和 jackson-module-jsonSchema 模块。例如,对于下面的类:
class实体{
private Long id;
私人列表<个人资料>型材;
// getters / setters
}
class配置文件{
私有字符串名称;
私有字符串值;
// 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));
$ / code $ / pre
打印下面的模式:
{
type:object,
properties:{
id:{
type:integer
},
profiles:{
type:array,
items:{
键入:object,
properties:{
name:{
type:string
},
value: {
type:string
}
}
}
}
}
}
I am using Gson
to serialize/deserialize java objects to json. I want to display it in UI
, and needs a schema to make a better description. This will allow me to edit objects and add more data than there actually is.
Can Gson
provide json schema?
Does any other framework has that capability?
解决方案 Gson library probably does not contain any feature like that but you can try to solve your problem with Jackson library and jackson-module-jsonSchema module. For example, for below classes:
class Entity {
private Long id;
private List<Profile> profiles;
// getters/setters
}
class Profile {
private String name;
private String value;
// getters / setters
}
this program:
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));
}
}
Prints below schema:
{
"type" : "object",
"properties" : {
"id" : {
"type" : "integer"
},
"profiles" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"name" : {
"type" : "string"
},
"value" : {
"type" : "string"
}
}
}
}
}
}
这篇关于从Java类创建JSON模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!