微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从Java类创建JSON模式

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

解决方法

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

原文地址:https://www.jb51.cc/java/123652.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐