将HashMap的ArrayList转换为JSON String

时间:2016-03-13 13:30:36

标签: java android arraylist hashmap

我想将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

1 个答案:

答案 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());

或者您可以使用Jackson Object Mapper:

Download Jackson Core

Download Jackson Mapper

将外部库添加到Eclipse Project

  

Adding a library/JAR to an Eclipse Android project

Java代码

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"}]