英文:
How to create a multiple JSON objects inside an Array in java selenium
问题
以下是翻译好的内容:
我希望使用一些循环以这种格式输出,因为数据包含超过20个对象。
"childTargets": [
{
"name": "true",
"rank": 86438458
},
{
"name": "false",
"rank": 86647857
}
]
我不希望以这种方式写,因为代码会太长。
.put(new JSONObject().put("name", "INDIA")
请帮助我。
英文:
I wanted the ouput in this format using some loop, because the data contains more than 20 objects.
"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
答案1
得分: 1
我会创建一个包含所有姓名和一个包含所有排名的数组,然后遍历它们。
以下是一个示例:
String[] names; // 所有的姓名
int[] ranks; // 所有的排名,第一个排名对应第一个姓名
JSONArray jsonArray = new JSONArray(); // 创建一个 JSONArray 对象。
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);
}
如果你有超过两个属性,考虑使用一个包含结构体或对象的列表,而不是分散的数组。
英文:
I would craete an aarry with all names and an array all ranks and the loop through them.
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.
答案2
得分: 0
You can use a library such as Gson
to marshal POJO's to json cleanly.
Define a java class such as:
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:
Gson gson = new Gson();
gson.toJson(childTargets);
You should get a json String in the form of:
{
"childTargets":[
{
"name":"obj1",
"rank":"rank1"
},
{
"name":"obj2",
"rank":"rank2"
}
]
}
英文:
You can use a library such as Gson
to marshal POJO's to json cleanly.
Define a java class such as:
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:
Gson gson = new Gson();
gson.toJson(childTargets);
You should get a json String in the form of:
{
"childTargets":[
{
"name":"obj1",
"rank":"rank1"
},
{
"name":"obj2",
"rank":"rank2"
}
]
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论