I'd like to use GSON to derialize:
"starterItems": {
"Appeltaart": 3,
"Soap_50": 3
}
...into a Guava ImmutableMap
:
private ImmutableMap<String,Integer> starterItems;
I thought I'd just use regular GSON map parsing, then make an immutable copy of the result, like this:
gb.registerTypeAdapter(ImmutableMap.class, new JsonDeserializer<ImmutableMap>() {
@SuppressWarnings("unchecked")
@Override public ImmutableMap deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return ImmutableMap.copyOf((Map) context.deserialize(json, Map.class));
}
});
But as expected, that was too simple (there is no type information). I get the error:
com.google.gson.JsonParseException: The JsonDeserializer MapTypeAdapter failed to deserialized json object {"Appeltaart":3,"Soap_50":3} given the type interface java.util.Map
Can I do what I want?
See Question&Answers more detail:os