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

2.7k Views Asked by At

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. json, json2, json3 - but none of those worked.

So how to convert full Map object with 0 values ?

2

There are 2 best solutions below

1
On BEST ANSWER

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

prints

{"Test":0,"Test2":1}
{"Test":0,"Test2":1,"Test3":null}
0
On

You can also try something like below;

List<Map<String, Object>> mapdataList = new ArrayList<Map<String, Object>>();

Map<String, Object> MapObj = new HashMap<String, Object>();
MapObj.put("windowHandle", "current");
MapObj.put("id", "{a67fc38c-10e6-4c5e-87dc-dd45134db570}");
mapdataList.add(MapObj);

Gson gson = new Gson();
JsonObject jObject = new JsonObject();
JsonParser jP = new JsonParser();
jObject.add("data", jP.parse(gson.toJson(mapdataList)));
System.out.println(jObject.toString());