动态创建 JSON 对象

Gia*_*nis 3 java android json

我正在尝试使用以下格式创建 JSON 对象。

{
"tableID": 1,
"price": 53,
"payment": "cash",
"quantity": 3,
"products": [
    {
        "ID": 1,
        "quantity": 1
    },
    {
        "ID": 3,
        "quantity": 2
    }
]
Run Code Online (Sandbox Code Playgroud)

}

  1. 我知道如何使用 JSONObject 和 JSONArray 静态地执行此操作。但我需要一种更动态的方式,因为必须实现产品数组,因此它有很多对象而不仅仅是 2 个。

  2. 有没有办法删除 JSONObject 的内容?例如我有以下 JSONobject

    { “ID”: 3, “数量”: 2 }

我可以以某种方式删除它的值,以便我可以在迭代中重用该对象吗?

小智 5

对于你的第一个问题,你可以像这样动态构建上面的 json 。

JSONObject jsonObject = new JSONObject();
jsonObject.put("tableID", 1);
jsonObject.put("price", 53);
jsonObject.put("payment", "cash");
jsonObject.put("quantity", 3);

JSONArray products = new JSONArray();

//product1
JSONObject product1 = new JSONObject();
product1.put("ID", 1);
product1.put("quantity", 1);
products.put(product1); //add to products

//product3
JSONObject product3 = new JSONObject();
product3.put("ID", 3);
product3.put("quantity", 2);
products.put(product3); //add to products

jsonObject.put("products", products); //add products array to the top-level json object
Run Code Online (Sandbox Code Playgroud)

对于第二个问题,如果您知道 JSONObject 的名称,则可以删除该元素。

jsonObject.remove("tableID"); // remove the tableID key/value pair
Run Code Online (Sandbox Code Playgroud)

或者,如果您想删除 JSONArray 的特定元素,那么您必须知道它在集合中的位置

jsonObject.getJSONArray("products").remove(1); //removes the second item in the collection which is the product3
Run Code Online (Sandbox Code Playgroud)