How to split Map items in Java?

Viewed 173

I have a map that produces json like this

{
    "item": {
        "Đã đặt cọc": 0,
        "Chờ duyệt": 0,
        "Mới tạo": 0,
        "Đang đặt hàng": 0,
        "Đang VC TQ-VN": 0,
        "Đang phát hàng": 0,
        "Đã nhận được hàng": 0,
        "Đã hủy": 0
    },
    "name": "Đơn mua hộ"
}

And I want it to be split to this

{
    "item": [
        {
            "name": "Đã đặt cọc",
            "count": "0"
        },
        {
            "name": "Chờ duyệt",
            "count": "0"
        },
         ...
    ],
    "name": "Đơn kí gửi"
}

I tried this code, but it didn't work

...
HashMap<String, Object> itemSell = new HashMap<>();
// Order Sell
orderSell.put("name", "Đơn mua hộ");
for (Map.Entry<String, Long> pair : reportsStaticSellEcomos.entrySet()) {
     itemSell.put("name", pair.getKey());
     itemSell.put("count", pair.getValue());
     orderSell.put("item", itemSell);
}
summary.add(orderSell);

The code above produces this

{
                "item": {
                    "name": "Đã hủy",
                    "count": 0
                },
                "name": "Đơn mua hộ"
            }

Yes, it only shows 1 item.

Please help me to get all of them, not only 1

2 Answers

Your item must be a collection of itemSell not an individual element.

Try with this

// Order Sell
orderSell.put("name", "Đơn mua hộ");
List<HashMap<String, Object>> items = new ArrayList<>(reportsStaticSellEcomos.entrySet().size());
for (Map.Entry<String, Long> pair : reportsStaticSellEcomos.entrySet()) {
     HashMap<String, Object> itemSell = new HashMap<>();
     itemSell.put("name", pair.getKey());
     itemSell.put("count", pair.getValue());
     items.add(itemSell);
}
orderSell.put("item", items);
summary.add(orderSell);

Also, using a HashMap<String, Object> to represent your Item is not very efficient or easy to understand. Instead you I suggest you create a class Item where you can encapsulate those fields.

public class Item {
  private final String name;
  private final int count;
  // constructor
  // equals and hashcode
  // getter, setter
}

Your loop repeatedly overwrites the "name" and "count" keys of that itemSell map. You want to use a List here.

...
// Order Sell
orderSell.put("name", "Đơn mua hộ");
List<Map<String, Object>> itemList = new ArrayList<>();
for (Map.Entry<String, Long> pair : reportsStaticSellEcomos.entrySet()) {
    Map<String, Object> itemSell = new HashMap<>();
    itemSell.put("name", pair.getKey());
    itemSell.put("count", pair.getValue());
    itemList.add(itemSell);
}
orderSell.put("item", itemList);
summary.add(orderSell);

You might also want to check out Jackson, which can automatically do this sort of thing based on a class structure.

class Order {
    String name;
    List<Item> items;
}

...

class Item {
    String name;
    Integer count;
}

...

Order order = ...;
objectMapper.writeValueAsString(order);
Related