two-phase deserialization of Map possible ?

23 views
Skip to first unread message

Martin Minka

unread,
Apr 10, 2013, 2:09:40 AM4/10/13
to googl...@googlegroups.com
  • my JSON string contains Map<String, Object>
  • based on key I know class of value
  • how to deserialize correctly such map ?
    • my preferred way would be to first deserialize value as string (Map<String, String>) and then deserialize each value with known class information

thank you for any advice,
Martin

Brandon Mintern

unread,
Apr 10, 2013, 6:19:40 PM4/10/13
to google-gson
The easiest way to get up and running is to parse it manually:

JsonParser jsonParser = new JsonParser();
Gson gson = new Gson();
// ...
JsonElement parsedJson = jsonParser.parse(jsonString);
JsonObject mapStringObj = parsedJson.getAsJsonObject(); // if the object is at the outer level
// Now iterate over the JsonObject
for (Entry<String, JsonElement> entry: mapStringObj.entrySet()) {
    String key = entry.getKey();
    // use your mapping from key to value class...
    Class valueClass = getClassFromKey(key);
    // Parse the JsonElement into an object of your desired class
    Object value = gson.fromJson(entry.getValue(), valueClass);
    // ... do stuffs with your key and value
}




--
You received this message because you are subscribed to the Google Groups "google-gson" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-gson...@googlegroups.com.
To post to this group, send email to googl...@googlegroups.com.
Visit this group at http://groups.google.com/group/google-gson?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Martin Minka

unread,
Apr 11, 2013, 5:31:51 AM4/11/13
to googl...@googlegroups.com
Brandon,
thank you, this is exactly what I was looking for.

Martin


2013/4/11 Brandon Mintern <min...@easyesi.com>
Reply all
Reply to author
Forward
0 new messages