java– 将HashMap的ArrayList转换为JSON字符串[复制]

java– 将HashMap的ArrayList转换为JSON字符串[复制],第1张

概述这个问题与以下内容完全相同:            >            ConvertingArrayListtoJSONArray                                    1个我想转换ArrayList<Hashmap<String,String>>到JSONArray.我用了JSONArrayarr

这个问题与以下内容完全相同:            >            Converting ArrayList to JSONArray                                    1个
我想转换ArrayList< Hashmap< String,String>>到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"}]

解决方法:

有很多方法可以实现这一目标.我将解释两种方式:

你可以这样做:

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

07002

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

以上是内存溢出为你收集整理的java – 将HashMap的ArrayList转换为JSON字符串[复制]全部内容,希望文章能够帮你解决java – 将HashMap的ArrayList转换为JSON字符串[复制]所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:http://outofmemory.cn/web/1115138.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-29
下一篇2022-05-29

发表评论

登录后才能评论

评论列表(0条)

    保存