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);
Related
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"));
I'm trying to read data from this API https://coinmarketcap.com/api/
For this endpoint https://api.coinmarketcap.com/v2/ticker/.
I'm having issues mapping the data field to a POJO. The field really contains an array of objects but in terms of the json it's not really defined as an array.
i.e. instead of
data: [{"id":"1","name":"some object"},{"id":"5","name":"another object"},...]
the json has named fields like so
data: {"1":{"id":"1","name":"some object"},"5":{"id":"5","name":"another object"},...}
I can manually parse this using
objectMapper.readTree(new URL("https://api.coinmarketcap.com/v2/ticker/"));
but is there a way automatically map these to a List?
You can parse it into a map (as #teppic said) and then get the map values as a list.
To deserialize into a map, you can see the answer from this question: Deserializing into a HashMap of custom objects with jackson
TypeFactory typeFactory = mapper.getTypeFactory();
MapType mapType = typeFactory.constructMapType(HashMap.class, String.class, Theme.class);
HashMap<String, Theme> map = mapper.readValue(json, mapType);
Assuming you have a class called Item with the id and name fields, you can do this:
String json = "{\"1\":{\"id\":\"1\",\"name\":\"some object\"},\"5\":{\"id\":\"2\",\"name\":\"another object\"}}";
ObjectMapper mapper = new ObjectMapper();
// create your map type <String, Item>
TypeFactory typeFactory = mapper.getTypeFactory();
MapType mapType = typeFactory.constructMapType(HashMap.class, String.class, Item.class);
HashMap<String, Item> map = mapper.readValue(json, mapType);
// get the list
List<Item> list = new ArrayList<Item>(map.values());
System.out.println(list);
Output:
[Item [id=1, name=some object], Item [id=2, name=another object]]
Your other option would be a custom deserializer, or reading the tree as you mentioned.
try this
String json = "[{\"name\":\"Steve\",\"lastname\":\"Jobs\"}]";
JsonArray jArray = (JsonArray)new JsonParser().parse(json);
String sName = jArray.get(0).getAsJsonObject().get("name").getAsString());
String sLastName = jArray.get(0).getAsJsonObject().get("lastname").getAsString());
see you later.
I used this code to compare two JSON object using Gson in Android:
String json1 = "{\"name\": \"ABC\", \"city\": \"XYZ\"}";
String json2 = "{\"city\": \"XYZ\", \"name\": \"ABC\"}";
JsonParser parser = new JsonParser();
JsonElement t1 = parser.parse(json1);
JsonElement t2 = parser.parse(json2);
boolean match = t2.equals(t1);
Is there any way two get the differences between two objects using Gson in a JSON format?
If you deserialize the objects as a Map<String, Object>, you can with Guava also, you can use Maps.difference to compare the two resulting maps.
Note that if you care about the order of the elements, Json doesn't preserve order on the fields of Objects, so this method won't show those comparisons.
Here's the way you do it:
public static void main(String[] args) {
String json1 = "{\"name\":\"ABC\", \"city\":\"XYZ\", \"state\":\"CA\"}";
String json2 = "{\"city\":\"XYZ\", \"street\":\"123 anyplace\", \"name\":\"ABC\"}";
Gson g = new Gson();
Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
Map<String, Object> firstMap = g.fromJson(json1, mapType);
Map<String, Object> secondMap = g.fromJson(json2, mapType);
System.out.println(Maps.difference(firstMap, secondMap));
}
This program outputs:
not equal: only on left={state=CA}: only on right={street=123 anyplace}
Read more here about what information the resulting MapDifference object contains.
I have a JsonObject :
{"result":[{"active":"true"}]}
How can I get value of active?
You can use Jackson
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> parsedMap = mapper.readValue(jsonString, new TypeReference<HashMap<String, Object>>() {
});
We get a Map with key value pairs. With your input you will get a Map<List<Map<String,String>>>. So to get "active", you can use something like parsedMap.get("result").get(0).get("active") (Note: This is just a pseudo code)
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).