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));