Thursday, October 31, 2024

How to convert JSON String to Java HashMap? Example

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.

    No comments :

    Post a Comment