如何为嵌套的 json 创建 JSONObject

我无法为嵌套的 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"

    }

  ]

}


守着一只汪
浏览 108回答 2
2回答

largeQ

您只需要创建一个新的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 oneSystem.out.println(jsonObject.toString());输出(带有一些格式):{"ballot":     {     "voteBallot":"string",     "voterEmail":"string"     }, "name":"new name", "description":"new election"}您也可以使用JSONArrayinstead 并以相同的方式附加它。

不负相思意

尝试这个:final JSONObject jsonObject = new JSONObject();&nbsp; &nbsp; Map<String, String> map = new HashMap<>();&nbsp; &nbsp; map.put("voteBallot", "string");&nbsp; &nbsp; map.put("voterEmail", "string");&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; jsonObject.put("name", "new name");&nbsp; &nbsp; &nbsp; &nbsp; jsonObject.put("description", "new election");&nbsp; &nbsp; &nbsp; &nbsp; jsonObject.put("candidates", new String[] {"new String"});&nbsp; &nbsp; &nbsp; &nbsp; jsonObject.put("ballotVisibility", "string");&nbsp; &nbsp; &nbsp; &nbsp; jsonObject.put("voterListVisibility", true);&nbsp; &nbsp; &nbsp; &nbsp; jsonObject.put("startingDate", LocalDateTime.now().atZone(ZoneOffset.UTC));&nbsp; &nbsp; &nbsp; &nbsp; jsonObject.put("ballot", new Map[]{map});&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("jsonObject = " + jsonObject);&nbsp; &nbsp; } catch (JSONException e) {&nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; }它不是所有领域,而是所有不同类型希望它有所帮助。输出:{&nbsp;&nbsp;&nbsp; &nbsp;"ballot":[&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; {&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"voteBallot":"string",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"voterEmail":"string"&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;],&nbsp; &nbsp;"candidates":[&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; "new String"&nbsp; &nbsp;],&nbsp; &nbsp;"ballotVisibility":"string",&nbsp; &nbsp;"name":"new name",&nbsp; &nbsp;"voterListVisibility":true,&nbsp; &nbsp;"description":"new election",&nbsp; &nbsp;"startingDate":"2019-07-05T22:34:58.750Z"}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java