动态生成JSON的最佳方法是什么

huangapple go评论69阅读模式
英文:

Best way to generate JSON dynamically

问题

我正在测试REST API。每个API都消耗不同类型的JSON有效负载。
我不想手动填写所有输入。因此,我希望动态生成JSON(例如,从文本文件中读取值并填入JSON结构),然后将生成的JSON作为请求主体传递给API。

如何做才是最佳方法?
有关工具或插件的任何推荐吗?

附注:JSON结构是嵌套且非常复杂的。

英文:

I am testing REST APIs. Each API consumers the different type of JSON payload.
I don't want to fill all input manually. So, I want to generate JSON dynamically (e.g. read values from a text file and fill in JSON structure) and then pass the generated JSON as Request Body in API.

What is the best way to do so?
Any recommendations for tools or a plugin?

P.S. The JSON structure in Nested and very complex.

答案1

得分: 1

这与我几周前遇到的情况相同。

我所做的可能对你也有帮助:

我在想要具有动态JSON的DTO中使用了 private Map<String, Object> data;

就像如果我的JSON是:

{
    "key": {
        "key1": ["1", "2", "3"]
    },
    "key2": {
    }
}

然后这个JSON将保存为一个Map,你可以使用它来解析你的JSON数据。

而且在解析时尝试使用 org.json

例如:

JSONObject jsonObject = new JSONObject(mapFromDTO);

现在你完全可以访问JSON,这是你的核心问题。

英文:

This is the same I was having some weeks ago.

What I did, might be helpful to you too:

I used private Map<String, Object> data;

in my DTO where I wanted to have Dynamic JSON.

like if my JSON is:

{
"key":{
"key1":["1","2","3"]
},
"key2":{
}
}

then this JSON will be saved as a Map which you can use to parse your JSON data.

and for parsing try using org.json

For example:

JSONObject jsonObject = new JSONObject(mapFromDTO);

And now you have full access to JSON, which was your core issue.

答案2

得分: 0

答案在于定义合约。首先决定在您的 JSON 中最大可能的值是什么。

例如,起初您可以决定以下合同:

{
    "id": 1,
    "name": "Username",
    "age": 30,
    "phone": 900000000
}

一旦合同确定下来,设计一个 POJO(普通旧 Java 对象)。这个 POJO 可以是非常复杂的数据结构,可以包含字段,也可以是字段(对象)的列表。这完全取决于您的业务。

然后,您可以编写一个 Java 服务,根据一些复杂的业务逻辑生成此 POJO。

一旦这个 POJO 被填充,可以使用像 Jackson 这样的第三方库将其转换为 JSON。

进一步阅读:
https://www.tutorialspoint.com/how-to-convert-java-object-to-json-using-jackson-library

英文:

The answer lies in defining the contract. Decide first on what are the maximum possible values in your JSON.

Example, for start you can decide on following contact:

{
	"id": 1,
	"name": "Username",
	"age": 30,
	"phone": 900000000
}

Once contract is finalised, design a POJO. This POJO can be very complex data structure which can have fields or may be list of fields (objects). This is totally dependent on your business.

You can then write a java service which can generate this POJO based on some complex business logic.

Once this POJO is populated use 3rd party library like jackson to convert it to JSON.

Further reading:
https://www.tutorialspoint.com/how-to-convert-java-object-to-json-using-jackson-library

huangapple
  • 本文由 发表于 2020年4月5日 14:25:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/61038815.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定