[英]How to create a multiple JSON objects inside an Array in java selenium
I wanted the ouput in this format using some loop , because the data contains more than 20 objects.我希望使用一些循环以这种格式输出,因为数据包含 20 多个对象。
"childTargets": [
{
"name": "true",
"rank": 86438458
},
{
"name": "false",
"rank": 86647857
}
]
i do not want in this way to right because code will be too long我不想以这种方式正确,因为代码会太长
.put(new JSONObject().put("name", "INDIA")
Please help me on this请帮助我
I would craete an aarry with all names and an array all ranks and the loop through them.我会创建一个包含所有名称的 aarry 和一个所有等级的数组,并通过它们循环。
Here is an example:这是一个例子:
String[] names; // all your Names
int[] ranks; // all your Ranks the first rank belongs to the first name.
JSONArray jsonArray = new JSONArray(); // Create an JSONArray Object.
for (int i = 0; i < names.length; i++) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", names[i]);
jsonObject.put("rank", ranks[i]);
jsonArray.add(jsonObject);
}
If you have more than two properties consider using one list with strucks or objects who contain all of them instead of sperad arrays.如果您有两个以上的属性,请考虑使用包含所有属性的列表或包含所有属性的对象,而不是sperad arrays。
You can use a library such as Gson
to marshal POJO's to json cleanly.您可以使用诸如Gson
之类的库将 POJO 干净地编组为 json。
Define a java class such as:定义一个 java class 例如:
public class ChildTargets {
private List<Target> children;
// getters and setters
public static class Target {
private String name;
private String rank;
// getters and setters
}
Then instantiate the ChildTargets class with any Target objects you want using a loop, then call:然后使用循环使用您想要的任何 Target 对象实例化 ChildTargets class,然后调用:
Gson gson = new Gson();
gson.toJson(childTargets);
You should get a json String in the form of:您应该得到一个 json 字符串,格式如下:
{
"childTargets":[
{
"name":"obj1",
"rank":"rank1"
},
{
"name":"obj2",
"rank":"rank2"
}
]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.