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 ?
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?
prints