亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何為嵌套的 json 創建 JSONObject

如何為嵌套的 json 創建 JSONObject

守著一只汪 2023-03-09 14:01:54
我無法為嵌套的 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"    }  ]}
查看完整描述

2 回答

?
largeQ

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 并以相同的方式附加它。


查看完整回答
反對 回復 2023-03-09
?
不負相思意

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"

}


查看完整回答
反對 回復 2023-03-09
  • 2 回答
  • 0 關注
  • 142 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號