[英]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 消息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.