我正在尝试使用以下格式创建 JSON 对象。
{
"tableID": 1,
"price": 53,
"payment": "cash",
"quantity": 3,
"products": [
{
"ID": 1,
"quantity": 1
},
{
"ID": 3,
"quantity": 2
}
]
我知道如何使用 JSONObject 和 JSONArray 静态地执行此操作。但我需要一种更动态的方式,因为产品数组必须是 已实现,因此它有很多对象,而不仅仅是 2 个。
有没有办法删除 JSONObject 的内容?例如我有 以下 JSONobject
{ “编号”:3, “数量”:2
我能否以某种方式删除它的值,以便我可以在迭代中重用该对象?
最佳答案
对于你的第一个问题,你可以像这样动态构建上面的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
对于第二个问题,如果你知道它的名字,你可以删除一个 JSONObject 的元素。
jsonObject.remove("tableID"); // remove the tableID key/value pair
或者,如果您想删除 JSONArray 的特定元素,那么您必须知道它在集合中的位置
jsonObject.getJSONArray("products").remove(1); //removes the second item in the collection which is the product3
关于java - 动态创建 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45043352/