有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

spring boot如何在Java中以编程方式从json模式生成json数据

我正在尝试为我的POST Api创建Body参数(JSON),这是一个JSON请求。我所有的模式都是JSON。我正试图列出一个不同的JSON测试数据列表,包括它的正流和负流

是否有使用Java编程生成/创建JSON数据的选项。我附加了一个小的Json模式(只是为了理解),但我的实际模式更复杂,有很多数组和嵌套的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

我的测试数据如下所示:

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

有什么建议我们怎样才能做到这一点? 注意:我使用的是Springboot,我对请求对象有完整的POJO


共 (2) 个答案

  1. # 2 楼答案

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

    POJO

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

    假对象

    使用特殊的库可以生成包含伪数据的对象,其中一些列在此处:

    生成JSON

    这非常简单,可以通过Jackson完成:

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