从 Java 类创建 JSON 模式

2022-09-04 05:55:42

我正在使用序列化/反序列化java对象到json。我想在 中显示它,并且需要一个架构来做出更好的描述。这将允许我编辑对象并添加比实际更多的数据。
可以提供 json 架构吗?
是否有任何其他框架具有该功能?GsonUIGson


答案 1

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"
          }
        }
      }
    }
  }
}

答案 2

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

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

您将获得以下JSON模式,用于Michal Ziober对此问题的回答中提到的类:

{
    "$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"}
    }
}