Converting JSON to a HashMap using Gson
Requesting data from a server in JSON format can be straightforward, but converting the JSON response into a more accessible format can sometimes present challenges. Consider the following JSON response:
{ "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" }
Using the GSON module, we can easily convert this JSON into a HashMap. Here's how:
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);
In this code, the TypeToken class is used to create a type specific to Map
The above is the detailed content of How Can I Convert JSON Data to a HashMap Using Gson?. For more information, please follow other related articles on the PHP Chinese website!