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
We can easily convert JSON data into a map because the JSON format is essentially a key-value pair grouping and the map also stores data in key-value pairs. Let's understand how we can use both JACKSON and Gson libraries to convert JSON data into a Map.
Serialization in the context of Gson means converting a Java object to its JSON representation. In order to do the serialization, we need to create the Gson object, which handles the conversion. Next, we need to call the function toJson() and pass the User object. Program output.
ConclusionBoth Gson and Jackson are good options for serializing/deserializing JSON data, simple to use and well documented. Advantages of Gson: Simplicity of toJson/fromJson in the simple cases. For deserialization, do not need access to the Java entities.
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.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With