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

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

Related

How to convert list map to json string and json to list map

I want to convert list map to json (First Activity)
then json to list map (Third Activity)
I am using built-in json library
Don't Use Any Third party library
Code to convert ListMap to json
{
}
else
{
HashMap<Object, Object> map = new HashMap<>();
map.put("title",list_string_title);
map.put("id",list_string_id);
JSONObject jsonObject = new JSONObject(map);
FileUtils.writeFile(getPathData(scr_id),jsonObject.toString());
}
When the program find the json file
I want it to add it into a listMap
You can iterate over the JSONObject and add it to the map, in your case your value is a list, it will be treated as JSONArray, you can try the following code
public Map<Object, Object> jsonToMap(JSONObject jsonObject) throws JSONException {
Iterator<String> itr = jsonObject.keys();
Map<Object, Object> mapFromJSON = new HashMap<Object,Object>();
while(itr.hasNext()) {
Object key = itr.next();
JSONArray jsonArray = (JSONArray) jsonObject.get((String) key);
ArrayList list = new ArrayList<Object>();
for(int i=0; i< jsonArray.length(); i++) {
list.add(jsonArray.get(i));
}
mapFromJSON.put(key, list);
}
return mapFromJSON;
}
if your list contains JSONObject, you can use recursion.
Need to pass a TypeReference to readValue with your output type
ObjectMapper mapper = new ObjectMapper();
List<Map<String, Object>> data = mapper.readValue(json, new TypeReference<List<Map<String, Object>>>(){});

Convert Json string into Hashmap of hashmap in java

I am new to json processing, below is the json string our clients send us, I want to
read this json string into a hashmap of hasmap so that even for the "Client"/"params" key below
I can access its key and value set and process them .
var incomingMessage =
"{
\"dev1\":\"NULL\",
\"devkp2\":\"val\",
\"compression\":\"NULL\",
\"subcode\":\"P_CODE\",
\"code\":\"PEB_USER\",
\"Client\":{
\"first_name\":\"Perf FN 422677\",
\"client_last_name\":\"DP_PSL\",
\"clientid\":\"780A832\",
\"email\":\"DP_PS#airb.com\"
},
\"clientsrc\":\"dev.client.notvalid\",
\"params\":{
\"Name\":\"ABC_PR\",
\"client_ID\":\"PSL\",
\"domain\":\"airb.com\"
}
}"
This is my current code which works fine for non-nested json strings (that is without the Client.params key in above json string):
public static void convertJsonStringToMap(String incomingMessage) {
HashMap<Object, Object> map = new HashMap<Object, Object>();
JSONObject jObject = new JSONObject(incomingMessage);
Iterator<?> keys = jObject.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
String value = jObject.getString(key);
map.put(key, value);
}
for (Map.Entry<Object, Object> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
}
I want to be able to similarly read nested keys like Client and params. I am using jdk11. I am fine with using jackson or google gson, both approaches would work.
Please help me with processing these nested json string.
A valid JSON string can be easily converted to a Map using Jackson ObjectMapper.
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> parsedMap = mapper.readValue(incomingMessage, Map.class);
It works for nested elements as well -
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String someJsonString = "{" +
"\"A\":\"1\"," +
"\"B\":2," +
"\"C\":" +
"{" +
"\"D\":\"4\"" +
"}" +
"}";
Map<String, Object> outputMap = mapper.readValue(someJsonString, Map.class);
System.out.println(outputMap);
}
Output:
{A=1, B=2, C={D=4}}

How to convert nested json into Map without typecasting using Gson

I am trying to understand/learn how to pull data from a weather API, i have successfully done that and i got a Json file filled with data. I managed with gson put the information into a Map.
But it also has nested json for key main were i'm pulling out value into what may by explicit typecasting.
The thing i would like to ask, is if there is a neater way of doing this and so that i don't need to do explicit type casting nested json into Map
Map<String, Object> resultMap = new Gson().fromJson(jsonString, new TypeToken<HashMap<String, Object>>() {
}.getType());
for (Map.Entry<String, Object> entry : resultMap.entrySet()) {
System.out.println(entry);
}
System.out.println(resultMap.get("temp"));
Map<String, Object> mainMap = (Map<String, Object>) resultMap.get("main");
System.out.println("Temp: " + mainMap.get("temp"));
This is my output in the console:
rain={}
visibility=10000.0
timezone=7200.0
main={temp=8.1, pressure=1007.0, humidity=93.0, temp_min=7.0, temp_max=10.0}
clouds={all=75.0}
sys={type=1.0, id=1788.0, country=SE, sunrise=1.571203601E9, sunset=1.571240388E9}
dt=1.571249075E9
coord={lon=18.06, lat=59.33}
weather=[{id=301.0, main=Drizzle, description=drizzle, icon=09n}]
name=Stockholm
cod=200.0
id=2673730.0
base=stations
wind={speed=3.6, deg=40.0}
null
Temp: 8.1
I would say you can convert the json string into Map<String, JsonElement> so that you have so methods to find nested object is JsonObject or JsonArray. So in the blow example main is key with JsonObject as value
main: {
temp:8.1,
pressure:1007.0,
humidity=93.0,
temp_min=7.0,
temp_max=10.0
}
You can parse the value into Map by using fromJson
Map<String, Object> resultMap = new Gson().fromJson(jsonString, new TypeToken<Map<String, Object>>() {
}.getType());
for (Map.Entry<String, Object> entry : resultMap.entrySet()) {
System.out.println(entry);
}
System.out.println(resultMap.get("temp"));
Map<String, Object> mainMap = new Gson().fromJson(resultMap.get("main").toString(), new TypeToken<Map<String, Object>>() {
}.getType());
System.out.println("Temp: " + mainMap.get("temp"));

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.

Gson to HashMap

Is there a way to convert a String containing json to a HashMap, where every key is a json-key and the value is the value of the json-key? The json has no nested values. I am using the Gson lib.
For example, given JSON:
{
"id":3,
"location":"NewYork"
}
resulting HashMap:
<"id", "3">
<"location", "NewYork">
Thanks
Use TypeToken, as per the GSON FAQ:
Gson gson = new Gson();
Type stringStringMap = new TypeToken<Map<String, String>>(){}.getType();
Map<String,String> map = gson.fromJson(json, stringStringMap);
No casting. No unnecessary object creation.
If I use the TypeToken solution with a Map<Enum, Object> I get "duplicate key: null".
The best solution for me is:
String json = "{\"id\":3,\"location\":\"NewYork\"}";
Gson gson = new Gson();
Map<String, Object> map = new HashMap<String, Object>();
map = (Map<String, Object>)gson.fromJson(json, map.getClass());
Result:
{id=3.0, location=NewYork}
I like:
private static class MyMap extends HashMap<String,String> {};
...
MyMap map = gson.fromJson(json, MyMap.class);

Categories