我想将JSONArray
转换为JSONArray array = new JSONArray(array_list);
。我用了
["{image=2130837526, category=Chairs, Quantity=1, price=400, name=chair, prodId=34}","{image=2130837566, category=Mirrors, Quantity=1, price=3000, name=La Fonda, prodId=35}"]
但它无法正常返回
cartitems=[{"name":"Chair","price":"1001","prodId":"2","category":"Chairs","image":"2130837519","Quantity":"1"},{"name":"Baxton Studio Club Chair","price":"4545","prodId":"5","category":"Chairs","image":"2130837521","Quantity":"1"}]
相反它应该返回
Si potrebbe comumente
答案 0 :(得分:9)
有很多方法可以实现这一目标。我将解释两种方式:
ArrayList<HashMap<String, String>> dataMap = new ArrayList<HashMap<String, String>>();
HashMap<String, String> data1 = new HashMap<String, String>();
data1.put("image", "2130837526");
data1.put("category", "Chairs");
data1.put("Quantity", "1");
HashMap<String, String> data2 = new HashMap<String, String>();
data2.put("image", "2130837566");
data2.put("category", "Mirrors");
data2.put("Quantity", "2");
dataMap.add(data1);
dataMap.add(data2);
List<JSONObject> jsonObj = new ArrayList<JSONObject>();
for(HashMap<String, String> data : dataMap) {
JSONObject obj = new JSONObject(data);
jsonObj.add(obj);
}
JSONArray test = new JSONArray(jsonObj);
System.out.println(test.toString());
ArrayList<HashMap<String, String>> dataMap = new ArrayList<HashMap<String, String>>();
HashMap<String, String> data1 = new HashMap<String, String>();
data1.put("image", "2130837526");
data1.put("category", "Chairs");
data1.put("Quantity", "1");
HashMap<String, String> data2 = new HashMap<String, String>();
data2.put("image", "2130837566");
data2.put("category", "Mirrors");
data2.put("Quantity", "2");
dataMap.add(data1);
dataMap.add(data2);
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(dataMap);
System.out.println(json);
两个选项都会打印出来:
[{"image":"2130837526","category":"Chairs","Quantity":"1"},{"image":"2130837566","category":"Mirrors","Quantity":"2"}]