I want to deserialize a JSON object (using GSON, because I already use it for searializing objects) to a general Map of type Map. It should create Objects of types that do correspond to the according JSON types, i.e. this JSON Object
{
"docID" : "a12345",
"relation" : ["1", "2", "3"],
"title" : { "de" : "German Title",
"en" : "English Title"}
}
should be deserialized in a Map with entries of the following types:
(String, String), (String, List), (String, Map).
I tried to use the following code:
class Dictionary_ extends HashMap {
// nothing to do
};
private static final GsonBuilder GSON_BUILDER = new GsonBuilder();
public Map deserializeJsonString(String jsonString) {
Dictionary_ d = new Dictionary();
return GSON_BUILDER.create().fromJson(jsonString, d.getClass());
}
But then the resulting types of created Objects are as follows:
(String, Object), (String, Object), (String, Object)
and I am not able to cast these objects into the corresponding "real" types, because I get class cast exceptions.
I am not able to use POJOs, since the data I am receiving does not have predefined structure in terms of class members.
So, how am I able to deserialize such generic data in according generic Java types?
Update:
I just tried to implement it using JSON Simple, and it works out of the box very easily by the following code:
Object ret = JSONValue.parse(jsonString);
return (List>) ret;
Why does it not work that easy with GSON???
解决方案
The structure that JSON.simple deserialized into was a Map, where each entry key is a String, and each entry value is either a simple data type or another Map.
Deserializing to such a structure with Gson is unfortunately not as simple as I think it should be, taking a few dozen lines of code. I posted an example of doing so at http://programmerbruce.blogspot.com/2011/06/gson-v-jackson.html. (Search for the phrase "Gson Code to turn any JSON object into a Map" to jump straight to the relevant example.)
That blog post also includes an example of using Jackson to accomplish the same task with just one line of code. (I highly recommend abandoning Gson in favor of Jackson, whenever possible.)