Mark Mark - 22 days ago 7x
Java Question

Gson: java.util.Map convert all key-value pairs

I have following code:

Collection<Product> products = productRepository.findProducts(from, pageSize);

Map<Product, BigDecimal> map = new TreeMap<>(new ProductComparator());
for (Product product : products) {
BigDecimal buyPrice = warehouseView.find(product.getId()).getBuyPrice();
map.put(product, buyPrice);

Gson gson = new Gson();
String json = gson.toJson(map);
TypeToken mapType = new TypeToken<Map<Product, BigDecimal>>(){}.getType();
String json2 = gson.toJson(map, mapType);
JsonElement json3 = gson.toJsonTree(map, mapType);

EXPLANATION: I have 5 products returned from DB, then for each of this products I call DB to get buy price. DB may return 0 - which indicates that given product not present in the warehouse.

So what I want to achieve: get json object, which has all 5 Products.

What is now: if for example for 3 products DB return 0 - I will get only 2 of my Products converted to json.

I've tried different versions of converting e.g.
- but none of those worked.

So how to convert full Map object with
values ?


You sure you're not getting null back from your service and/or are you sure that Product is not null for some of the entries?

    Map<String, BigDecimal> test = new TreeMap<>();
    test.put("Test", BigDecimal.ZERO);
    test.put("Test2", BigDecimal.ONE);
    test.put("Test3", null);

    Gson gson = new Gson();

    Type mapType = new TypeToken<HashMap<String, Integer>>() {}.getType();
    System.out.println(gson.toJson(test, mapType));

    Gson gson2 = new GsonBuilder().serializeNulls().create();
    System.out.println(gson2.toJson(test, mapType));