在JSONArray中添加新属性

时间:2017-08-16 09:56:29

标签: java arrays json

我有以下情况

"sections": [
      {
        "id": XXXX,
        "tipology": "TIPOLOGY"
      },
      {
        "id": XXXX,
        "tipology": "TIPOLOGY"
      },
      {"num": 2}
    ],

我正在使用JSONArray和JSONObject。有没有办法做到这一点?

"sections": [
      "num": 2,
      {
        "id": XXXX,
        "tipology": "TIPOLOGY"
      },
      {
        "id": XXXX,
        "tipology": "TIPOLOGY"
      },

    ],

2 个答案:

答案 0 :(得分:0)

我相信你正试图计算内部的数组。我想你可以在下面这样做。

{
    "sections": [{
            "id": "XXXX",
            "tipology": "TIPOLOGY"
        },
        {
            "id": "XXXX",
            "tipology": "TIPOLOGY"
        }
    ],
    "num": 2
}

OR

{
"sections": [{
        "id": "XXXX",
        "tipology": "TIPOLOGY"
    },
    {
        "id": "XXXX",
        "tipology": "TIPOLOGY"
    }, {
        "id": "COUNT",
        "num": 2
    }
]

}

答案 1 :(得分:0)

您可以使用以下格式的json对象,希望它适合您。

{     “sections”:{         “num”:100,         “值”:[{             “id”:“XXXX”,             “tipology”:“TIPOLOGY”         }]     } }

以上程序的java代码如下。

import org.json.*;

class test {
    public static void main(String[] args) throws JSONException {
        JSONObject sections = new JSONObject();
        JSONObject obj = new JSONObject();

        obj.put("num", new Integer(2));
        JSONArray array = new JSONArray();
        JSONObject value = new JSONObject();
        value.put("id", "XXXX");
        value.put("tipology", "TIPOLOGY");

        array.put(value);
        obj.put("values", array);

        sections.put("sections", obj);
        System.out.print(sections);
    }
}