How to split Map items in Java? - java

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

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

How to wrap object in array in java?

I'm making a code to send data to the payment gateway. I am a beginner in using java. I'm having a bit of trouble working with objects in an array in the item_details parameter. I've made the code as below.
public KeyValuePair<String, String> requestSnapToken(String orderNo,
BigDecimal grossAmount, int paymentMethodId,
String firstName,
String email,
List<FormCartLine> itemDetails
) {
return FAILSAFE_EXECUTOR.get(() -> {
String midtransOrderId = orderNo;
Builder<String, Object> custDetailBuilder = new ImmutableMap.Builder<String, Object>()
.put("first_name", firstName)
.put("last_name", "");
Builder<String, Object> itemDetailsBuilder = new ImmutableMap.Builder<String, Object>();
for (int i = 0; i < itemDetails.size(); i++) {
FormCartLine line = itemDetails.get(i);
int row = i + 1;
itemDetailsBuilder.put($("id%s", row), line.getProductId())
.put($("price%s", row), line.getUnitPricePreTax())
.put($("quantity%s", row), line.getQty())
.put($("name%s", row), line.getName())
.put($("brand%s", row), line.getBrandName())
.put($("category%s", row), line.getCategoryName());
}
Builder<String, Object> payloadBuilder = new ImmutableMap.Builder<String, Object>()
.put("transaction_details", new ImmutableMap.Builder<String, Object>()
.put("order_id", midtransOrderId)
.put("gross_amount", String.valueOf(grossAmount.longValue()))
.build())
.put("item_details", itemDetailsBuilder.build())
});
}
I tried to debug from the code that I made, the payload looks like this. This is not what I wanted..
"transaction_details" : {
"order_id" : "S415",
"gross_amount" : "194547"
},
"item_details" : {
"id1" : "001",
"price1" : 200,
"quantity1" : 1,
"name1" : "Dummy 1",
"brand1" : "Dummy",
"category1" : "Dummies",
"id2" : "002",
"price2" : 300,
"quantity2" : 1,
"name2" : "Dummy 2",
"brand2" : "Dummy",
"category2" : "Dummies"
},
what i want is like below. How do I implement it in java?
"transaction_details" : {
"order_id" : "S415",
"gross_amount" : "194547"
},
"item_details" : [{
"id" : "001",
"price" : 200,
"quantity" : 1,
"name" : "Dummy 1",
"brand" : "Dummy",
"category" : "Dummies"
},
{
"id" : "002",
"price" : 300,
"quantity" : 1,
"name" : "Dummy 2",
"brand" : "Dummy",
"category" : "Dummies"
}
]
Build separate maps for each of your objects and put those maps into a list. Immutability is probably not required, so I'll simplify by using an ArrayList:
final List<Map<String, Object>> itemDetailsList = new ArrayList<>(itemDetails.size());
for (final FormCartLine line : itemDetails) {
itemDetailsList.add(Map.ofEntries(
Map.entry("id", line.getProductId()),
Map.entry("price", line.getUnitPricePreTax()),
// etc.
));
}
// ...
Builder<String, Object> payloadBuilder = new ImmutableMap.Builder<String, Object>()
// .put(...)
.put("item_details", itemDetailsList)
Note that the map returned by Map.ofEntries cannot hold null values, so if that's a requirement, you need to switch to a HashMap<String, Object> or another map type with support for null values.
Of course, you can use an ImmutableMap.Builder too if you prefer or the loop could be converted to use the Java stream API.

How to convert a list of java objects to Map<String, Map<String, String>>

I have a list of java objects as below:
[
{
id: "frwfhfijvfhviufhbviufg",
country_code: "DE",
message_key: "key1",
translation: "This is the deutsch translation"
},
{
id: "dfregregtegetgetgttegt",
country_code: "GB",
message_key: "key1",
translation: "This is the uk translation"
},
{
id: "frffgfbgbgbgbgbgbgbgbg",
country_code: "DE",
message_key: "key2",
translation: "This is the again deutch translation"
}
]
How can I convert this into a Map<String, Map<String, String>> like below:
{
"DE": {
"key1": "This is the deutsch translation",
"key2": "This is the again deutch translation"
},
"GB": {
"key1": "This is the uk translation"
}
}
I am new to java and below is my code but the code is not correct:
Map<String, Translations> distinctTranslations = customTranslationsEntities
.stream().collect(Collectors.groupingBy(
CustomTranslationsEntity::getCountryCode,
Collectors.toMap(
CustomTranslationsEntity::getMessageKey,
CustomTranslationsEntity::getTranslation),
)))
where Translations is proto buffer message like below:
message Translations {
map<string, string> translations = 1;
}
Here map<string, string> translations means map like "key1", "This is the deutsch translation"...like this.
The output should be Map<String, Map<String,String>>:
Map<String, Map<String,String>>
distinctTranslations = customTranslationsEntities
.stream()
.collect(Collectors.groupingBy(CustomTranslationsEntity::getCountryCode,
Collectors.toMap(
CustomTranslationsEntity::getMessageKey,
CustomTranslationsEntity::getTranslation,
(v1,v2)->v1)));
I added a merge function, in case there are duplicate keys.
If you want to do it without using streams then
private List<MyObject> list = // Your object List
private Map<String, Map<String, String>> map = new HashMap<>();
for(MyObject object : list){
Map<String, String> localMap;
localMap = map.getOrDefault(object.country_code, new HashMap<>());
localMap.put(object.message_key, object.translation);
if(!map.containsKey(object.country_code)){
map.put(object.country_code, localMap);
}
}

JSON to Java: How to model lists of objects into generic model

I'm making a spreadSheet using SpreadJS, and I should be able to to add, delete and change the value of a key nested inside many objects. Here is how my json is formatted:
{
"version": "10.0.0",
"sheets": {
"Sheet1": {
"name": "Sheet1",
"data": {
"dataTable": {
"0": {
"0": {
"value": 129
}
}
}
},
"selections": {
"0": {
"row": 0,
"rowCount": 1,
"col": 0,
"colCount": 1
},
"length": 1
},
"theme": "Office",
"index": 0
}
}
}
The data represents, say, the value of each cell in the spreadSheet [0,0], [0,1], [1,1] ...etc. I want to parse this data into a List of generic model, for the field dataTable i would like to represent it like this: Map<Integer, Map<Integer, ValueObj>> for example in this case <0, <0, 129>> but i didn 't find how to do that and how my model would likely be.
I am new to JSON any help is appreciated! Thanks
Then to handle data, you can have a generic class like :
class CellData<T> {
T data;
}
Then read as below :
String jsonInput = "{ \"0\": { \"0\": { \"value\": 129 } } }";
ObjectMapper mapper = new ObjectMapper();
TypeReference<HashMap<Integer,HashMap<Integer,CellData<Integer>>>> typeRef =
new TypeReference<HashMap<Integer, HashMap<Integer, CellData<Integer>>>>() {};
Map<Integer, Map<Integer, CellData<Integer>>> map = mapper.readValue(jsonInput, typeRef);

How I get only value ignoring the key

I have a json array in database. I want to get only value ignoring the key and send it to ajax call.
Json string I have while saving:
{
"cells":
[
{
"type": "devs.TooledModel",
"position":
{
"x": 200,
"y": 100
},
"size":
{
"width": 71,
"height": 100
},
".":
{
"magnet": false
}
}
]
}
I want to return the exact json array from database but I am getting a key appended because I am using a map in java servlet to retrieve json:
List<Map<String, Object>> result = new ArrayList<>();
while (rSet.next()) {
Map<String, Object> row = new HashMap<>();
row.put("JSON_Diagram", rSet.getString("JSON_INFO"));
result.add(row);
}
json received: JSON_Diagram: "cells%5B0%5D%5Btype%5D=devs.TooledModel&cells..
How do I remove the key JSON_Diagram and get only value ? Tried with Object value = result.get(0); but didn't work
You need to get a list of all the keys, loop over them and add them to your map and if you need only value add values only to list as shown in the example below:
Map<String,Object> row = new HashMap<String,Object>();
Iterator iter = rSet.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = rSet.getString(key);
row.put(key,value);
result.add(value);
}
So once you have the map just do a a map.values.
[http://docs.oracle.com/javase/7/docs/api/java/util/Map.html#values()][1]
Then just use the resultant collection!

iterate a List<HashMap<String, String>> values using java

I have a json response like this
{
"queryPath": "/api/",
"nId": "f084f5ad24fcfaa9e9faea0",
"statusCode": 707
"statusMessage": "Success",
"results": {
"data": [
{
"id": "10248522500798",
"capabilities": [
"men",
"women"
],
"name": "errt2"
},
{
"id": "418143778",
"capabilities": [
"dog",
"cat"
],
"name": "Livin"
}
]
}
}
Here am adding results.data to a list as follows
private List<HashMap<String, String>> episodes = new ArrayList<HashMap<String, String>>();
episodes =helper.getJSONValue(response, "results.data");
public <T>T getJSONValue(Response res, String path ){
String json = res.asString();
JsonPath jpath = new JsonPath(json);
return jpath.get(path);
}
so episodes contains all data i mean all results.data
While i debuging am getting this way
[{id=10248522500798, name=errt2, capabilities=[men, women]}, {id=418143778, name=Livin, capabilities=[dog, cat]}]
Here i have capabilities [men, women] and [dog, cat].i need to check capability contains men or dog.
How can i do that?
If i were you i haven't done this..
Use gson and map your json into a java model. It's way better. Afterwards you can access all your model parts with getters and setters.
MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2
As you see it's very simple :)
But if you want to iterate a list that contains a map you can use code block below:
List<Map<String, String>> test = new ArrayList<Map<String, String>>();
for( Map<String, String> map : test ){
for( Entry<String, String> entry : map.entrySet() ){
System.out.println( entry.getKey() + " : " + entry.getValue() );
}
}
With the code above you can get all the entry's keys and values and check them.
Edit:
You have to change your List to List<Map<String,Object>> after that:
List<Map<String, Object>> test = new ArrayList<Map<String, Object>>();
for( Map<String, Object> map : test ){
for( Entry<String, Object> entry : map.entrySet() ){
if( entry.getKey().equalsIgnoreCase( "capabilities" ) ){
List<String> myCapabilities = ( List )entry.getValue();
if( myCapabilities.contains( "dog" ) && myCapabilities.contains( "cat" ) ){
// BLA BLA
}
}
}
}
It's a nasty way.. I recommend you to use gson..

Categories