How can I convert LinkedHashMap to JSONObject - java

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"
}

Related

Converting HashMap into JSONArray, Values are not coming properly

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.

How to check if an item in a JsonElement exists in a seperate JsonArray?

I have a JsonElement:
JsonElement testCaseParametersJson = batchItem.getTestCase().getToolParameters().get("testCaseParameters");
of which assigns the following:
["dessert", "place", "tvShow"]
And I have a JsonArray:
JsonObject testParametersJson = batchItem.getTestParameters().getAsJsonObject();
of which assigns the following:
{"dessert": "cookies", "tvShow": "survivor", "color" : "blue"}
I'd appreciate some advice on how to check if the key in the JsonArray exists as an item in the JsonElement.
Using Gson library, you can get the String values from your JSONElement / JSONObject and do the following:
String jsonObject = "{\"dessert\": \"cookies\", \"tvShow\": \"survivor\", \"color\" : \"blue\"}";
String jsonArray = "[\"dessert\", \"place\", \"tvShow\"]";
Map<String, String> objMap = new Gson().fromJson(jsonObject, new TypeToken<HashMap<String, String>>() {}.getType());
List<String> arrayVals = new Gson().fromJson(jsonArray, new TypeToken<List<String>>(){}.getType());
for(Entry<String, String> entry : objMap.entrySet()) {
for (String val : arrayVals) {
if (entry.getKey().equals(val)) {
System.out.println("Found value in key set: " + val);
}
}
}
Code can be summarized, and if using Java 8, you can try "forEach" loop according to your needs.

Putting JSON values into Hashmap

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>>() {
});

How to parse JSON object into `Map<String, HashSet<String>>`

I'd like to parse this JSON object:
"{
\"Rao\":[\"Q7293658\",\"\",\"Q7293657\",\"Q12953055\",\"Q3531237\",\"Q4178159\",\"Q1138810\",\"Q579515\",\"Q3365064\",\"Q7293664\",\"Q1133815\"],
\"Hani Durzy\":[\"\"],
\"Louise\":[\"\",\"Q1660645\",\"Q130413\",\"Q3215140\",\"Q152779\",\"Q233203\",\"Q7871343\",\"Q232402\",\"Q82547\",\"Q286488\",\"Q156723\",\"Q3263649\",\"Q456386\",\"Q233192\",\"Q14714149\",\"Q12125864\",\"Q57669\",\"Q168667\",\"Q141410\",\"Q166028\"],
\"Reyna\":[\"Q7573462\",\"Q2892895\",\"Q363257\",\"Q151944\",\"Q3740321\",\"Q2857439\",\"Q1453358\",\"Q7319529\",\"Q733716\",\"Q16151941\",\"Q7159448\",\"Q5484172\",\"Q6074271\",\"Q1753185\",\"Q7319532\",\"Q5171205\",\"Q3183869\",\"Q1818527\",\"Q251862\",\"Q3840414\",\"Q5271282\",\"Q5606181\"]
}"
and with that data generate a Map<String, HashSet<String>>.
Essentially I want to reverse this procedure.
All the code for this project can be found on my github page here, it's quite short.
update
File f = new File("/home/matthias/Workbench/SUTD/nytimes_corpus/wdtk-parent/wdtk-examples/JSON_Output/user.json");
String jsonTxt = null;
if (f.exists())
{
InputStream is = new FileInputStream("/home/matthias/Workbench/SUTD/nytimes_corpus/wdtk-parent/wdtk-examples/JSON_Output/user.json");
jsonTxt = IOUtils.toString(is);
}
//System.out.println(jsonTxt);
Gson gson=new Gson();
Map<String, HashSet<String>> map = new HashMap<String, HashSet<String>>();
map=(Map<String, HashSet<String>>) gson.fromJson(jsonTxt, map.getClass());
//// \\ // ! PRINT IT ! // \\ // \\ // \\ // \\ // \\ // \\
for (Map.Entry<String, HashSet<String>> entry : map.entrySet())
{
System.out.println(entry.getKey()+" : " + Arrays.deepToString(map.entrySet().toArray()) );
}
Using Gson
Gson gson = new Gson();
String json = "<YOUR_JSON_STRING_HERE>";
Map<String, HashSet<String>> map = new HashMap<String, HashSet<String>>();
map = (Map<String, HashSet<String>>) gson.fromJson(json, map.getClass());
Update:
Use TypeToken
Type type = new TypeToken<Map<String, HashSet<String>>>(){}.getType();
map = (Map<String, HashSet<String>>) gson.fromJson(json, type);
Or you could parse it...
Create an object of JSONObject
Create an object of HashMap
Iterate over jsonObj.keys() and for every key get value like
jsonObj.getString(key).
Put it in the map like map.put(key, value).

Needed to parse JSON Objects Present under LinkedList and calculate a field value

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.

Categories