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
I know this is a fairly old question, but I was searching for a solution to generically deserialize nested JSON to a Map
, and found nothing.
The way my yaml deserializer works, it defaults JSON objects to Map
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 to Map
and JsonArray
s to Object[]
s, where all the children are similarly deserialized.
private static class NaturalDeserializer implements JsonDeserializer
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:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Object.class, new NaturalDeserializer());
Gson gson = gsonBuilder.create();
And then call it like:
Object natural = gson.fromJson(source, Object.class);
I'm not sure why this is not the default behavior in gson, since it is in most other semi-structured serialization libraries...