1
"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,在我的第二个位置 price=60.00, product_code=55,quantity=10,total:600.00 等等。他们中的任何一个都知道答案帮助我。

4

1 回答 1

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));
于 2013-01-10T13:23:54.920 回答