Java 动态创建JSON对象
我正在尝试使用以下格式创建JSON对象Java 动态创建JSON对象,java,android,json,Java,Android,Json,我正在尝试使用以下格式创建JSON对象 { "tableID": 1, "price": 53, "payment": "cash", "quantity": 3, "products": [ { "ID": 1, "quantity": 1 }, { "ID": 3, "quantity": 2 } ] } 我知道如何使用JSONObject和JSONArray静态地完成这项工作。但是我需要一种更
{
"tableID": 1,
"price": 53,
"payment": "cash",
"quantity": 3,
"products": [
{
"ID": 1,
"quantity": 1
},
{
"ID": 3,
"quantity": 2
}
]
}
我是否可以删除它的值,以便在迭代中重用该对象?尝试将JSON数据构造为字符串:
String json = "{" +
"\"tableID\": 1," +
"\"price\": 53," +
"\"payment\": \"cash\"," +
"\"quantity\": 3," +
"\"products\": [";
for (int i = 0; i < 100; i++) {
json += "{ \"ID\": 3, \"quantity\": 2 }";
if(i != 100) json += ",";
}
json += "]}";
注意:请参阅kws,了解更具可读性的方法。是的,作为一个对象,您可以更改其内容。如果能回答你的问题,那就太好了
JSONArray jsArray = (JSONArray) json.get("products");
JSONObject js1 = jsArray.getJSONObject(0);
System.out.println("0: "+js1);
jsArray.remove(0);
JSONObject js2 = jsArray.getJSONObject(0);
System.out.println("1: "+js2);
jsArray.remove(0);
因此,您可以根据您对第一个问题的偏好迭代该数组或将其放入列表中 您可以使用创建java类,它将创建2个类,一个用于属性(
tableId…
),另一个用于产品,并且只在主类中包含产品数组
关于第二个问题
您可以忽略它
products[0]
和忽略products[1](Id:3)
对于您的第一个问题,您可以像这样动态构建上面的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
哇,我用js而不是java写了一个完整的长答案 只需使用HashMap和Google提供的GSON库 请看这里: 您可以将对象动态创建为hashMap,随意添加和删除产品。然后使用toJson()方法将对象转换为JSON字符串
(或者从任何用fromJson()读入HashMap的JSON字符串开始)然后随意操作它并将其返回到字符串。由于产品是一个数组,您可以对其进行迭代,如果您知道要删除的id,则可以将其删除。感谢您的回复,但我并没有试图从数组中删除任何内容。我正在尝试构建一个JSONObject,就像我发布的一样。该问题有Java标记。这不是Java。
jsonObject.getJSONArray("products").remove(1); //removes the second item in the collection which is the product3