繁体   English   中英

如何在 Java 中以编程方式从 Json Schema 生成 json 数据

[英]How to generate json data from Json Schema Programmatically in Java

我正在尝试为我的 POST Api 创建 Body-parameter(JSON) ,这是一个 JSON 请求。 我所拥有的只是 JSON Schema 。 我正在尝试为它提出涵盖正流和负流的不同 JSON 测试数据的列表。

是否有任何选项可以使用 Java 以编程方式生成/创建 JSON 数据? . 我附上了一个小的 Json 模式(只是为了理解目的),但我的实际模式更复杂,有很多 Array 和 Nested Json 的 .

我的 Json 架构:

{
"$schema": "http://json-schema.org/draft-07/schema",
"$id": "http://example.com/example.json",
"type": "object",
"title": "The Root Schema",
"description": "The root schema comprises the entire JSON document.",
"required": [
    "FirstName",
    "LastName",
    "Age",
    "Interest"
],
"properties": {
    "FirstName": {
        "$id": "#/properties/FirstName",
        "type": "string",
        "title": "The Firstname Schema",
        "description": "An explanation about the purpose of this instance.",
        "default": "",
        "examples": [
            "Vijay"
        ]
    },
    "LastName": {
        "$id": "#/properties/LastName",
        "type": "string",
        "title": "The Lastname Schema",
        "description": "An explanation about the purpose of this instance.",
        "default": "",
        "examples": [
            "Karthik"
        ]
    },
    "Age": {
        "$id": "#/properties/Age",
        "type": "integer",
        "title": "The Age Schema",
        "description": "An explanation about the purpose of this instance.",
        "default": 0,
        "examples": [
            30
        ]
    },
    "Interest": {
        "$id": "#/properties/Interest",
        "type": "array",
        "title": "The Interest Schema",
        "description": "An explanation about the purpose of this instance.",
        "default": [],
        "items": {
            "$id": "#/properties/Interest/items",
            "type": "string",
            "title": "The Items Schema",
            "description": "An explanation about the purpose of this instance.",
            "default": "",
            "examples": [
                "Food",
                "movie",
                "Learning",
                "VideoGames"
            ]
        }
    }
}

enter code here

我的 TestData 看起来像:

 {
"FirstName":"Vivi",
"LastName":"Karrri",
"Age":30,
"Interest":["Food","movie","Learning","VideoGames"]
}

任何建议我们如何实现这一目标? 注意:我正在使用 Springboot 并且我有完整的请求对象的 POJO

您可以生成伪造的 java 对象,然后将它们映射到 JSON。

POJO

如果您已经有与模式匹配的 POJO,那么我们可以跳过这一步。 如果没有,例如从模式生成 POJO,可以使用这个库: jsonschema2pojo

假货

可以用一个特殊的库来生成带有假数据的对象,这里列出了其中的一些:

生成 JSON

这很简单,可以用 Jackson 完成:

ObjectMapper objectMapper = new ObjectMapper();
ObjectWriter prettyPrinter = objectMapper.writerWithDefaultPrettyPrinter();
String json = prettyPrinter.writeValueAsString(yourFakeObject);

如果您有 json 模式,那么您可以直接从中生成示例 JSON 消息。

https://github.com/jignesh-dhua/json-generator

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM