gpt4 book ai didi

java - JSON 对象如果重复则不应添加

转载 作者:行者123 更新时间:2023-12-01 11:16:32 25 4
gpt4 key购买 nike

Scanner input = new Scanner(System.in);
JSONArray finaljson = new JSONArray();
for (int j = 0; j < 2; j++) {
System.out.println("Enter Version Name");
String vName = input.next();
System.out.println("Enter Version Key");
;
String vKey = input.next();
JSONObject root = new JSONObject();
if (!root.has("versionName")) {
root.put("versionName", vName);
root.put("versionKey", vKey);
}

JSONArray issue = new JSONArray();
System.out.println("Enter Epic Name");
String epicName = input.next();

System.out.println("Enter Epic Key");
String epicKey = input.next();
JSONObject epicData = new JSONObject();
epicData.put("epickKey", epicKey);
epicData.put("epickName", epicName);
issue.put(epicData);

root.put("issue", issue);
finaljson.put(root);
}

System.out.println("JSON DATA" + finaljson.toString());

嘿,制作一个 JSON,从代码来看,如果用户多次输入版本名称,则不应添加到根 json 对象中。那么如何限制它。

[
{
"versionKey": "vkey1",
"issue": [
{
"epickName": "e1",
"epickKey": "ekey1"
}
],
"versionName": "v1"
},
{
"versionKey": "vkey1",
"issue": [
{
"epickName": "e2",
"epickKey": "eky2"
}
],
"versionName": "v1"
}
]

但想要

[
{
"versionKey": "vkey1",
"issue": [
{
"epickName": "e1",
"epickKey": "eky1"
},
{
"epickName": "e2",
"epickKey": "eky2"
}
],
"versionName": "v1"
}
]

你能帮我制作这种类型的动态 json 数据吗

最佳答案

如果我理解正确,您希望输出类似于问题中的第二个 JSON 数组。改变循环位置应该可以解决问题:

Scanner input = new Scanner(System.in);
JSONArray finaljson = new JSONArray();

System.out.println("Enter Version Name");
String vName = input.next();
System.out.println("Enter Version Key");;
String vKey = input.next();
JSONObject root = new JSONObject();
if (!root.has("versionName")) {
root.put("versionName", vName);
root.put("versionKey", vKey);
}

JSONArray issue = new JSONArray();
for (int j = 0; j < 2; j++) {
System.out.println("Enter Epic Name");
String epicName = input.next();

System.out.println("Enter Epic Key");
String epicKey = input.next();
JSONObject epicData = new JSONObject();
epicData.put("epickKey", epicKey);
epicData.put("epickName", epicName);
issue.put(epicData);
}

root.put("issue", issue);
finaljson.put(root);

System.out.println("JSON DATA" + finaljson.toString());

我用你的输入进行了测试。以下是格式化的 JSON 输出:

[
{
"issue": [
{
"epickKey": "eky1",
"epickName": "e1"
},
{
"epickKey": "eky2",
"epickName": "e2"
}
],
"versionName": "vkey1",
"versionKey": "v1"
}
]

关于java - JSON 对象如果重复则不应添加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31766514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com