Suppose you have a JSON String, may be a web-service response and you want to create a Map out of it, where key should be the fields and value should be values of those fields e.g. if given JSON String is following :
{
"zip": "90210",
"city": "Beverly Hills"
"state": "CA"
"timeZone": "P"
}
then your HashMap should contain 4 mappings where keys are zip, city, state and timeZone, all of String type and corresponding values.
Though you can write your method to do this conversion by first parsing the JSON String into Java Object and then building the Map, but that's neither elegant nor very efficient.
Instead, you should use Gson library from Google, which provides this functionality out-of-box.
In gson, you can do something like below to convert a JSON String to Java HashMap :
Map<String, Object> retMap = new Gson()
.fromJson(jsonString,
new TypeToken<HashMap<String, Object>>() {}.getType());
Of course, this is one of the simplest JSON String, it doesn't contain any JSON array, neither it contain nested objects or nested array, but given Gson is handling all that for you, can be relax.
But, if you write your own method, then you need to keep all that things in mind so that your code can handle all kinds of JSON String.
That's all about how to convert a JSON String to HashMap in Java. I am not sure if other popular JSON libraries like Jackson and JSON-simple provides this kind of functionality out of box, if you do, please let us know.
- How to format JSON String in Java?
- How to parse JSON using Gson?
- 20 JSON Interview Questions with Answers
- How to parse a JSON array in Java?
- How to Iterate over JSONObject in json-simple Java?
- How to return JSON from Spring MVC controller?
- How to download Jackson JAR files in Java
- How to Solve UnrecognizedPropertyException: Unrecognized field, not marked as ignorable -
- How to convert JSON to HashMap in Java?
- 10 Things Java developers should learn
- How to ignore unknown properties while parsing JSON in Java?
No comments:
Post a Comment