gpt4 book ai didi

java - 如何为嵌套 json 创建 JSONObject

转载 作者:行者123 更新时间:2023-12-02 03:25:25 25 4
gpt4 key购买 nike

我无法为嵌套 json 创建 json 对象。

我可以为基本 json 创建 json 对象。我无法添加更多字段。

final JSONObject jsonObject = new JSONObject();
try {

jsonObject.put("name", "new name");
jsonObject.put("description", "new election");

} catch (JSONException e) {
e.printStackTrace();
}

这是我的 json:

{
"name": "string",
"description": "string",
"candidates": [
"string"
],
"ballotVisibility": "string",
"voterListVisibility": true,
"startingDate": "2019-07-05T20:09:23.311Z",
"endingDate": "2019-07-05T20:09:23.311Z",
"isInvite": true,
"isRealTime": true,
"votingAlgo": "string",
"noVacancies": 0,
"ballot": [
{
"voteBallot": "string",
"voterEmail": "string"
}
]
}

最佳答案

您只需创建一个新的 JSONObject,然后使用新名称将其附加到父对象。下面显示了附加选票的示例:

JSONObject jsonObject = new JSONObject();
JSONObject ballot = new JSONObject();
ballot.put("voteBallot","string");
ballot.put("voterEmail","string");

jsonObject.put("name", "new name");
jsonObject.put("description", "new election");

jsonObject.put("ballot", ballot); //Append the other JSONObject to the parent one

System.out.println(jsonObject.toString());

输出(带有一些格式):

{
"ballot":
{
"voteBallot":"string",
"voterEmail":"string"
},
"name":"new name",
"description":"new election"
}

您还可以使用 JSONArray 代替,并以相同的方式附加它。

关于java - 如何为嵌套 json 创建 JSONObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56908812/

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