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.
JSON is a text based object that different from 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.
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.
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);
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());
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