Android: Using Gson To Parse A Response With Dynamic Fields
I need to parse a JSON response regarding events in an agenda, of which a field is dynamic. This field changes depending on the month in which the event takes place. Now I've been
Solution 1:
Since the month data are not valid java identifiers, you 'll probably have to use custom serialization with GSON. You're talking about using Map objects but if you are going to do that you may as well us the org.json objects like JSONObject which are basically built on maps/hashtables anyway.
Solution 2:
If all your fields, as you have said, are dynamic then you can create a super set of all fields in a pojo. But that doesn't really help and I think the Map
is the best solution. With GSON, you can do
Typetype = newTypeToken<Map<String, String>>(){}.getType();
Map<String, String> map = gson.fromJson("{'key1':'123','key2':'456'}", type);
This will return a map of strings.
I haven't actually used GSON to do this before though. I have been very happy with Jackson lib and with that you can do
newObjectMapper().readValue("...json...", Map.class)
The above will return a map of maps which is what you want.
Post a Comment for "Android: Using Gson To Parse A Response With Dynamic Fields"