"order_item" : [{"price":"250.00","product_code":"1","quantity":"2","
total":"500.00"},
{"price":"200.00","product_**code":"2","quantity":"1","**total":"200.00"} ]
}
我必须将我的哈希地图数组列表转换为上面的json数组格式。在我的数组列表的第一个位置,我的设置如price = 250.00,product_code = 1,quantity = 2,total:500.00,在我的第二个位置价格= 60.00,product_code = 55,数量= 10,总数:600.00等等。他们中的任何人都知道答案帮帮我。
答案 0 :(得分:6)
public class Product
{
private String price;
private String product_code;
private String quantity;
private int total;
public Product(String price, String product_code, String quantity, int total)
{
this.price = price;
this.product_code = product_code;
this.quantity = quantity;
this.total = total;
}
}
业务逻辑
new Gson().toJson(map);
使用
Product pr1 = new Product("str1", "str1", "str1", 250);
Product pr2 = new Product("str2", "str2", "str2", 200);
List<Product> list = new ArrayList<Product>();
list.add(pr1);
list.add(pr2);
Map<String, List<Product>> map = new HashMap<String, List<Product>>();
map.put("order_item", list);
System.out.println(new Gson().toJson(map));
编辑(使用json.org)
Map<String, String> jsonMap1 = new HashMap<String, String>();
jsonMap1.put("price", "250.00");
jsonMap1.put("product_code", "1");
jsonMap1.put("quantity", "2");
jsonMap1.put("total", "200");
Map<String, String> jsonMap2 = new HashMap<String, String>();
jsonMap2.put("price", "250.00");
jsonMap2.put("product_code", "1");
jsonMap2.put("quantity", "2");
jsonMap2.put("total", "200");
JSONObject json1 = new JSONObject(jsonMap1);
JSONObject json2 = new JSONObject(jsonMap2);
JSONArray array = new JSONArray();
array.put(json1);
array.put(json2);
JSONObject finalObject = new JSONObject();
finalObject.put("order_item", array);
System.out.println(finalObject.toString());
EDIT2 (使用Gson)
Map<String, String> jsonMap1 = new HashMap<String, String>();
jsonMap1.put("price", "250.00");
jsonMap1.put("product_code", "1");
jsonMap1.put("quantity", "2");
jsonMap1.put("total", "200");
Map<String, String> jsonMap2 = new HashMap<String, String>();
jsonMap2.put("price", "250.00");
jsonMap2.put("product_code", "1");
jsonMap2.put("quantity", "2");
jsonMap2.put("total", "200");
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
list.add(jsonMap1);
list.add(jsonMap2);
Map<String, List<Map<String, String>>> map = new HashMap<String, List<Map<String, String>>>();
map.put("order_item", list);
System.out.println(new Gson().toJson(map));