从Java类创建JSON模式

编程入门 行业动态 更新时间:2024-10-09 12:32:20
本文介绍了从Java类创建JSON模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我使用 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模式

本文发布于:2023-11-26 09:03:22,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模式   Java   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!