Am getting response from Elasticsearch with duplicates, to avoid that i used Hashmap implementation and i put all the values into the HashMap object.
After that am iterating over the HashMap object to convert into JSONArray.
Am geting one unique record from distinctObjects (HashMap Object). But after if convert into JSONArray., the length of JSONArray shows 2 it suppose to be 1 and am printing the JSONArray, it shows like below.
JSONArray --->[{"code":"VA1125-GGA-1","id":"code"},{"code":"12816","id":"id"}]
Expected Result should be :
JSONArray --->[{"code":"VA1125-GGA-1","id":"12816"}]
Please find my code below.
JSONObject responseObj;
JSONArray responseArray = new JSONArray();
Map<String, Object> distinctObjects = null;
SearchHit[] searchHits2 = searchResponse2.getHits().getHits();
for (SearchHit hit2 : searchHits2) {
Map<String, Object> sourceAsMap2 = hit2.getSourceAsMap();
distinctObjects = new HashMap<String, Object>();
distinctObjects.put("id", sourceAsMap2.get("id").toString());
distinctObjects.put("code", sourceAsMap2.get("code").toString());
}
Iterator it = distinctObjects.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
responseObj = new JSONObject();
responseObj.put("id", pair.getKey());
responseObj.put("code", pair.getValue());
responseArray.put(responseObj);
it.remove(); // avoids a ConcurrentModificationException
}
System.out.println("Link ID List Size --->"+responseArray.length());
System.out.println("JSONArray --->"+responseArray.toString());
It looks like you're adding both code and id as top level entries to your distinctObjects map which is why you're getting two objects back. Assuming you want to de-dup based on ID your first loop should look something like:
for (SearchHit hit2 : searchHits2) {
Map<String, Object> sourceAsMap2 = hit2.getSourceAsMap();
distinctObjects = new HashMap<String, Object>();
distinctObjects.put(sourceAsMap2.get("id"), sourceAsMap2.get("code").toString());
}
That will give you one entry in distinctObjects for every unique id with a value of the code.
If you wanted you could also add sourceAsMap2 as the value in distinctObjects to maintain the full response if you need more than just the code in downstream processing.
Related
ArrayList entries, and this entries is of LinkedHashMap type, I want to convert this into jsonOject for the use, how can I do this?
for(Object entry : entries){
JSONObject entryToProcess = (JSONObject) entry;
}
Hi this conversion utility should do.
What happens here is that you call the method .getKeys() on the LinkedHashMap object to get all the keys. Then for each key you retrieve the information from the LinkedHashMap and you put it inside the JSONObject
// Your input LinkedHashMap
LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<String, String>();
// Providing general values for the test
linkedHashMap.put("First key", "First value");
linkedHashMap.put("Second key", "Second value");
linkedHashMap.put("Third key", "Third value");
// Initialization of the JSONObject
JSONObject jsonObject = new JSONObject();
// for-each key in the LinkedHashMap get the value and put both of
// them into the JSON
for (String key : linkedHashMap.keySet()) {
jsonObject.put(key, linkedHashMap.get(key));
}
The part you care about should be the for loop.
Cheers,
Simple JSONObject constructor would do the trick
for(Object entry : entries){
JSONObject entryToProcess = new JSONObject((LinkedHashMap)entry);
}
Sample:
LinkedHashMap<String,Object> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("A",1);
linkedHashMap.put("some key","some value");
Map<String, String> someMap = new HashMap<>();
someMap.put("map-key-1","map-value-1");
someMap.put("map-key-2","map-value-2");
linkedHashMap.put("another key",someMap);
JSONObject jsonObject = new JSONObject(linkedHashMap);
System.out.println(jsonObject.toJSONString());
Output:
{
"another key": {
"map-key-1": "map-value-1",
"map-key-2": "map-value-2"
},
"A": 1,
"some key": "some value"
}
I am trying to put a Map<String, Object> to the Map<String, Map<String, Object>>.
Below is the code:
Map<String, Object> createmap = new HashMap<String, Object>();
Map<String, Object> result = new HashMap<String, Object>();
for (int j=0 ; j<jsonarr2.size(); j++ )
{
JSONObject jsonobj2 = (JSONObject) jsonarr2.get(j);
Iterator<String> key2 = jsonobj2.keySet().iterator();
while (key2.hasNext()) {
String k2 = key2.next();
createmap.put(k2, jsonobj2.get(k2));
}
System.out.println("Print J:" + j + " CREATE MAP:" + createmap);
result.put(Integer.toString(j),createmap);
System.out.println("result :" + result);
}
the For loop runs 5 times and there will be five records in createmap.
But the map result is using the key as 0 always and hence only the last record of the createmap is available in the result map.
Output of the print statement inside the loop:
Print J:0 CREATE MAP:{vsan_name={"value":{"0":{"sequence":0,"value":"VSAN0001","timestamp":1548643752}}}}
result : {0={vsan_name={"value":{"0":{"sequence":0,"value":"VSAN0001","timestamp":1548643752}}}}}
Print J:1 CREATE MAP:{vsan_name={"value":{"0":{"sequence":0,"value":"VSAN0002","timestamp":1548643752}}}}
result : {0={vsan_name={"value":{"0":{"sequence":0,"value":"VSAN0002","timestamp":1548643752}}}}}
Print J:2 CREATE MAP:{vsan_name={"value":{"0":{"sequence":0,"value":"VSAN0003","timestamp":1548643752}}}}
result : {0={vsan_name={"value":{"0":{"sequence":0,"value":"VSAN0003","timestamp":1548643752}}}}}
Print J:3 CREATE MAP:{vsan_name={"value":{"0":{"sequence":0,"value":"VSAN0004","timestamp":1548643752}}}}
result : {0={vsan_name={"value":{"0":{"sequence":0,"value":"VSAN0004","timestamp":1548643752}}}}}
Print J:4 CREATE MAP:{vsan_name={"value":{"0":{"sequence":0,"value":"VSAN0005","timestamp":1548643752}}}}
result : {0={vsan_name={"value":{"0":{"sequence":0,"value":"VSAN0005","timestamp":1548643752}}}}}
But the final Map is having only
{0={vsan_name={"value":{"0":{"sequence":0,"value":"VSAN0005","timestamp":1548643752}}}}}
The key remains as 0 all the time and the value is updating to the same key.
Looks like jsonarr2.size() is 1 and hence, the loop runs only once (even though the nested JSONObject has 5 keys.
Also, you might be getting records with same key across different json objects from json array. Try moving instantiation of createMap inside the for loop, e.g.:
Map<String, Object> result = new HashMap<String, Object>();
for (int j=0 ; j<jsonarr2.size(); j++ )
{
Map<String, Object> createmap = new HashMap<String, Object>();
JSONObject jsonobj2 = (JSONObject) jsonarr2.get(j);
Iterator<String> key2 = jsonobj2.keySet().iterator();
while (key2.hasNext()) {
String k2 = key2.next();
createmap.put(k2, jsonobj2.get(k2));
}
System.out.println("Print J:" + j + " CREATE MAP:" + createmap);
result.put(Integer.toString(j),createmap);
}
I have JSON value like below,
{ "emp_id": 1017,
"emp_name": "karthik Y",
"emp_designation": "Manager",
"department": "JavaJson",
"salary": 30000,
"direct_reports":
[
"Nataraj G",
"Kalyan",
"Mahitha"
]
}
HashMap < String, String[] >input1 = new HashMap < String, String[] >();
input1.put("empid","1017");
input1.put("emp_name","karthik");
input1.put("emp_designation","manager");
input1.put("salary","30000");
now I want to add next array that is direct_report to put as next key and value(entire array shoud be come one key and value). Someone please help out.
Hashmap is a key/value storage, where keys are unique. You can convert your JSON to string and then store it as a value to the hashmap. For example something like below:
public static void main(String[] args) {
String json = "{ \"emp_id\": 1017,"
+ "\"emp_name\": \"karthik Y\","
+ "\"emp_designation\": \"Manager\","
+ "\"department\": \"JavaJson\","
+ "\"salary\": 30000,"
+ "\"direct_reports\": ["
+ "\"Nataraj G\","
+ "\"Kalyan\","
+ "\"Mahitha\"]}";
HashMap<String, String> jsonStore = new HashMap<String, String>();
jsonStore.put("myJson", json);
System.out.println(jsonStore.get("myJson"));
}
You need can also use the 'org.json' library to
Create JSON object manually
Convert existing JSONObject to String representation
Convert JSON string to JSONObject
You can also have the following solution:
JSONObject jsonObject = new JSONObject();
jsonObject.put("empt_id", 1017);
jsonObject.put("emp_name", "karthik");
HashMap<String, JSONObject> jsonObjectStore = new HashMap<String, JSONObject>();
jsonObjectStore.put("myJsonObject", jsonObject);
HashMap<JSONObject, String> jsonObjectStore2 = new HashMap<JSONObject, String>();
jsonObjectStore2.put(jsonObject, "myJson");
Make sure that you download the org.json jar file and put it in your classpath to be able to use the JSONObject. You can download the jar from here.
In order to put each of those values into map as single key/value entry. You have mentioned it yourself, it should work without any problem. See below methods:
Method 1
Everything in Java is Object, String inherits Object, String[] inherits object. You can have the following solution:
HashMap<String, Object> myObjectStore4 = new HashMap<String, Object>();
String[] directReports4 = new String[]{"Natraj G", "Kalyan", "Mahitha"};
myObjectStore4.put("emp_id", new String("123"));
myObjectStore4.put("emp_name", new String("Raf"));
// others ....
myObjectStore4.put("directReports", directReports4);
Method 2
To store the fields as key/value and if you can afford converting the array to String (which represents all array elements comma separated then use this method).
HashMap<String, String> myObjectStoreTwo = new HashMap<String, String>();
String[] directReports2 = new String[]{"Natraj G", "Kalyan", "Mahitha"};
myObjectStoreTwo.put("emp_id", "123");
myObjectStoreTwo.put("emp_name", "Raf");
myObjectStoreTwo.put("salary", "222");
//Converts array to comma separated String
myObjectStoreTwo.put("directReports",Arrays.toString(directReports2));
Method 3
In the expense of having Hash Map to store String key and Array value. You have to put other elements as array too.
HashMap<String, String[]> myObjectStore3 = new HashMap<String, String[]>();
String[] directReports3 = new String[]{"Natraj G", "Kalyan", "Mahitha"};
myObjectStore3.put("emp_id", new String[]{123 + ""});
myObjectStore3.put("salary", new String[]{32312 + ""});
myObjectStore3.put("directReports", directReports3);
Use a jackson ObjectMapper. Try if this works
String json = "{....}"
HashMap<String,Object> mappedVals = new ObjectMapper().readValue(
json ,
new TypeReference<HashMap<String,Object>>() {
});
I have got a Map with a key and a list of JSONObjects as shown
Map<String, LinkedList<JSONObject>> vendorOrdersMap = new LinkedHashMap<String, LinkedList<JSONObject>>();
I need to calculate price present under each LinkedList of a Vendor , to know which vendor has got the highest price .
Map<String, LinkedList<JSONObject>> vendorOrdersMap = new LinkedHashMap<String, LinkedList<JSONObject>>();
// For Vendor 1
JSONObject vendor1 = new JSONObject();
vendor1.put("price", "100");
JSONObject vendor2 = new JSONObject();
vendor2.put("price", "200");
LinkedList<JSONObject> list1vendor1 = new LinkedList<JSONObject>();
list1vendor1.add(vendor1);
list1vendor1.add(vendor2);
// For Vendor2
JSONObject vendor3 = new JSONObject();
vendor1.put("price", "200");
JSONObject vendor4 = new JSONObject();
vendor2.put("price", "300");
LinkedList<JSONObject> list1vendor2 = new LinkedList<JSONObject>();
list1vendor2.add(vendor3);
list1vendor2.add(vendor4);
// Add them to the Map
vendorOrdersMap.put("Vendor1", list1vendor1);
vendorOrdersMap.put("Vendor2", list1vendor2);
//I started with this but couldn't able to proceed further with this
for (Map.Entry<String, LinkedList<JSONObject>> entry : vendorOrdersMap.entrySet())
{
String key = entry.getKey();
LinkedList<JSONObject> jsonobj = entry.getValue();
}
Your last line was:
LinkedList<JSONObject> jsonobj = entry.getValue();
After this, iterate over list again like:
for(JSONObject obj : jsonobj) {
Then get values out of JSONObject like:
String price = obj.getString("price");
Then do your comparison to calculate highest price.
I have this arraylist and another for hashmap
ArrayList<HashMap<String, String>> agentList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> agentproperty = new HashMap<String, String>();
I have received jArray from php file. and trying to put it in the array using hashmap.
JSONArray jArray = jsonObj.getJSONArray(TAG_AGENT);
String id = null;
String name = null;
for (int i = 0; i < jArray.length(); i++) {
JSONObject a = jArray.getJSONObject(i);
id = a.getString(TAG_AGENTID);
name = a.getString(TAG_NAME);
agentproperty.put("AGENTID", id);
agentproperty.put("NAME", name);
Log.d("id",id);
Log.d("name",name);
agentList.add(agentproperty);
}
Log.d("firstperson",String.valueOf(agentList.get(0)));
Log.d("secondperson",String.valueOf(agentList.get(1)));
I can get
id 1, hame cathy; id 2, name john
for the log inside loop. But from the last log, I am getting
id 2, name john; id 2, name john
It seems the value of agentproperty is changed even after adding in arraylist.
I tried taking the agentList.add(agentproperty); outside of loop. Didnt work. Only inserts the last value (id 2, name john). Any idea how can i populate this array with all the values I get from loop. I will need to use agentList in listview.
yes it is. You have to create a new instance of the HashMap at every iteration, otherwise you will override the value for a given key, if an entry already exists
Move
HashMap<String, String> agentproperty = new HashMap<String, String>();
inside the for loop