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.
This is more of addendum to Kevin Dolan's answer than a complete answer, but I was having trouble extracting the type from the Number. This is my solution:
I know this is a fairly old question, but I was searching for a solution to generically deserialize nested JSON to a
Map<String, Object>
, and found nothing.The way my yaml deserializer works, it defaults JSON objects to
Map<String, Object>
when you don't specify a type, but gson doesn't seem to do this. Luckily you can accomplish it with a custom deserializer.I used the following deserializer to naturally deserialize anything, defaulting
JsonObject
s toMap<String, Object>
andJsonArray
s toObject[]
s, where all the children are similarly deserialized.The messiness inside the
handlePrimitive
method is for making sure you only ever get a Double or an Integer or a Long, and probably could be better, or at least simplified if you're okay with getting BigDecimals, which I believe is the default.You can register this adapter like:
And then call it like:
I'm not sure why this is not the default behavior in gson, since it is in most other semi-structured serialization libraries...
I used this code:
I had the exact same question and ended up here. I had a different approach that seems much simpler (maybe newer versions of gson?).
with the following json
The following
outputs
You could dynamically check using instanceof when navigating your jsonObject. Something like
It works for me, so it must work for you ;-)
Try this, it will worked. I used it for Hashtable.
Replace KioskStatusResource to your class and Integer to your key class.