解析 JSON Schema 文档生成 Java 代码

根据 JSON Schema 文档生成 Java 代码,使用的是 GitHub 上的开源项目 jsonschema2pojo,该项目有多种使用方式,详细看文档,这里采用引入依赖方式

步骤如下

  1. 项目中引入依赖,准备对应的 JSON Schema 文档

  2. 编写解析 JSON Schema 文档 的代码

  3. 执行程序即可

详细步骤

引入依赖

<dependencies>
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.9.0</version>
    </dependency>
    <dependency>
        <groupId>org.jsonschema2pojo</groupId>
        <artifactId>jsonschema2pojo-core</artifactId>
        <version>1.1.2</version>
    </dependency>
</dependencies>

解析 JSON Schema 文档的核心代码

生成实例类代码

import com.sun.codemodel.JCodeModel;
import org.jsonschema2pojo.*;
import org.jsonschema2pojo.rules.RuleFactory;

import java.io.File;
import java.io.IOException;
import java.net.URL;

public class Example {

    public static void main(String[] args) throws IOException {
        JCodeModel codeModel = new JCodeModel();
//        URL source = Example.class.getResource("/demo.json");
        final URL source = new File("E:\\workspace\\local\\sdk-third\\chenfu\\src\\main\\resources\\demo.json").toURI().toURL();

        GenerationConfig config = new DefaultGenerationConfig() {

            @Override
            public boolean isIncludeConstructorPropertiesAnnotation() {
                return false;
            }

            @Override
            public boolean isIncludeToString() {
                return false;
            }

            @Override
            public boolean isIncludeHashcodeAndEquals() {
                return false;
            }


            @Override
            public boolean isIncludeAllPropertiesConstructor() {
                return true;
            }

            @Override
            public boolean isIncludeGeneratedAnnotation() {
                return false;
            }

            @Override
            public boolean isUseInnerClassBuilders() {
                return super.isUseInnerClassBuilders();
            }

            @Override
            public boolean isSerializable() {
                return true;
            }

            @Override
            public boolean isUseDoubleNumbers() {
                return false;
            }

            @Override
            public boolean isUseBigDecimals() {
                return true;
            }

            @Override
            public boolean isUseLongIntegers() {
                return super.isUseLongIntegers();
            }

        };

//        final AbstractAnnotator annotator = new Jackson2Annotator(config);
        final GsonAnnotator annotator = new GsonAnnotator(config);

        SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, annotator, new SchemaStore()), new SchemaGenerator());
        mapper.generate(codeModel, "ClassName", "com.chenfu", source);

        final File path = new File("E:\\workspace\\local\\sdk-third\\chenfu\\src\\main\\resources");
        codeModel.build(path);
    }

}

测试案例

demo.json
{
  "type": "object",
  "properties": {
    "code": {
      "type": "integer",
      "format": "int32",
      "description": "返回标记:成功=0,失败=1"
    },
    "data": {
      "type": "boolean",
      "description": "数据"
    },
    "msg": {
      "type": "string",
      "description": "返回信息"
    },
    "ok": {
      "type": "boolean"
    }
  },
  "title": "响应信息",
  "description": "响应信息主体"
}
Demo.java
package com.chenfu;

import java.io.Serializable;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;


/**
 * 响应信息
 * <p>
 * 响应信息主体
 */
public class Demo implements Serializable {

    private final static long serialVersionUID = -8028169617875788750L;
    /**
     * 返回标记:成功=0,失败=1
     */
    @SerializedName("code")
    @Expose
    private Integer code;
    /**
     * 数据
     */
    @SerializedName("data")
    @Expose
    private Boolean data;
    /**
     * 返回信息
     */
    @SerializedName("msg")
    @Expose
    private String msg;
    @SerializedName("ok")
    @Expose
    private Boolean ok;

    /**
     * 返回标记:成功=0,失败=1
     */
    public Integer getCode() {
        return code;
    }

    /**
     * 返回标记:成功=0,失败=1
     */
    public void setCode(Integer code) {
        this.code = code;
    }

    /**
     * 数据
     */
    public Boolean getData() {
        return data;
    }

    /**
     * 数据
     */
    public void setData(Boolean data) {
        this.data = data;
    }

    /**
     * 返回信息
     */
    public String getMsg() {
        return msg;
    }

    /**
     * 返回信息
     */
    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Boolean getOk() {
        return ok;
    }

    public void setOk(Boolean ok) {
        this.ok = ok;
    }

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
可以使用以下步骤将 JSON Schema 转换为 Java 对象: 1. 首先,你需要使用 JSON Schema 生成器来创建一个 JSON Schema。这个生成器可以生成符合 JSON Schema 标准的 JSON 文件。 2. 然后,你需要使用一个 Java 库来将 JSON Schema 转换为 Java 对象。有很多 Java 库可以完成这个任务,其中一些比较流行的包括 Jackson 和 Gson。 3. 最后,你需要使用 Java 对象来解析和处理 JSON 数据。可以使用相同的库来完成此任务,也可以使用其他库,比如 org.json。 下面是一个使用 Jackson 库将 JSON Schema 转换为 Java 对象的示例代码: ```java // 导入所需的库 import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.module.jsonSchema.JsonSchema; import com.fasterxml.jackson.module.jsonSchema.JsonSchemaGenerator; // 创建一个 ObjectMapper 对象 ObjectMapper mapper = new ObjectMapper(); // 生成 JSON Schema JsonSchemaGenerator schemaGen = new JsonSchemaGenerator(mapper); JsonSchema schema = schemaGen.generateSchema(YourClass.class); // 将 JSON Schema 转换为 JsonNode 对象 JsonNode schemaNode = mapper.valueToTree(schema); // 将 JsonNode 对象转换为 Java 对象 YourClass yourObject = mapper.treeToValue(schemaNode, YourClass.class); ``` 在这个示例中,我们使用 Jackson 库来生成 JSON Schema,然后将其转换为 JsonNode 对象,最后将 JsonNode 对象转换为 Java 对象。在实际应用中,你需要将代码中的 YourClass 替换为你要使用的类的名称。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值