Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert JSON to a HashMap using Gson?

I'm requesting data from a server which returns data in the JSON format. Casting a HashMap into JSON when making the request wasn't hard at all but the other way seems to be a little tricky. The JSON response looks like this:

{      "header" : {          "alerts" : [              {                 "AlertID" : "2",                 "TSExpires" : null,                 "Target" : "1",                 "Text" : "woot",                 "Type" : "1"             },             {                  "AlertID" : "3",                 "TSExpires" : null,                 "Target" : "1",                 "Text" : "woot",                 "Type" : "1"             }         ],         "session" : "0bc8d0835f93ac3ebbf11560b2c5be9a"     },     "result" : "4be26bc400d3c" } 

What way would be easiest to access this data? I'm using the GSON module.

like image 981
Mridang Agarwalla Avatar asked May 06 '10 07:05

Mridang Agarwalla


People also ask

Does JSON use Hashmap?

JSON is a text based object that different from HashMap.

How does JSON define Hashmap?

new JSONObject(hashmap) to Convert Hashmap to JSON Object The most traditional way of converting a hashmap to JSON object is by calling JSONObject() and then passing the hashmap. Let's take a look at an example that creates a hashmap and then prints it in JSON format.

Can we convert JSON to Java object?

The ObjectMapper class is the most important class in the Jackson library. We can convert a JSON to Java Object using the readValue() method of ObjectMapper class, this method deserializes a JSON content from given JSON content String.


2 Answers

Here you go:

import java.lang.reflect.Type; import com.google.gson.reflect.TypeToken;  Type type = new TypeToken<Map<String, String>>(){}.getType(); Map<String, String> myMap = gson.fromJson("{'k1':'apple','k2':'orange'}", type); 
like image 181
Tito Avatar answered Oct 29 '22 17:10

Tito


This code works:

Gson gson = new Gson();  String json = "{\"k1\":\"v1\",\"k2\":\"v2\"}"; Map<String,Object> map = new HashMap<String,Object>(); map = (Map<String,Object>) gson.fromJson(json, map.getClass()); 
like image 25
Angel Avatar answered Oct 29 '22 18:10

Angel