2 回答

TA貢獻2039條經驗 獲得超8個贊
您只需要創建一個新的JSONObject,然后使用新名稱將其附加到父對象。下面顯示了一個示例附加ballot:
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"
}
您也可以使用JSONArrayinstead 并以相同的方式附加它。

TA貢獻1777條經驗 獲得超10個贊
嘗試這個:
final JSONObject jsonObject = new JSONObject();
Map<String, String> map = new HashMap<>();
map.put("voteBallot", "string");
map.put("voterEmail", "string");
try {
jsonObject.put("name", "new name");
jsonObject.put("description", "new election");
jsonObject.put("candidates", new String[] {"new String"});
jsonObject.put("ballotVisibility", "string");
jsonObject.put("voterListVisibility", true);
jsonObject.put("startingDate", LocalDateTime.now().atZone(ZoneOffset.UTC));
jsonObject.put("ballot", new Map[]{map});
System.out.println("jsonObject = " + jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
它不是所有領域,而是所有不同類型希望它有所幫助。輸出:
{
"ballot":[
{
"voteBallot":"string",
"voterEmail":"string"
}
],
"candidates":[
"new String"
],
"ballotVisibility":"string",
"name":"new name",
"voterListVisibility":true,
"description":"new election",
"startingDate":"2019-07-05T22:34:58.750Z"
}
添加回答
舉報