java - 动态创建 JSON 对象

标签 java android json

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

{
"tableID": 1,
"price": 53,
"payment": "cash",
"quantity": 3,
"products": [
    {
        "ID": 1,
        "quantity": 1
    },
    {
        "ID": 3,
        "quantity": 2
    }
]

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

  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/

相关文章:

android - 使用cordova在android中添加google plus

android - 使用 resConfigs 时保留一种语言的所有区域资源

android - 在 Android 中收到的第二个最近的彩信而不是最近的彩信

java - 重置计数器或让它增加并使用模数是否更有效

java - 当有来自 java 程序的连接时,Oracle 不提供 osuser

java - 堆栈中的push(int[][])复制相同的值Java

java - jackson-mapper 版本 1.9.12 EnumDeserializer 问题

java - 在java中选择随机数

java - 我收到错误解析数据 org.json.JSONException

C lib直接从文件流中读取和解析JSON