Serialize complex objects containing Maps

101 views
Skip to first unread message

Markos

unread,
Oct 8, 2008, 5:51:49 AM10/8/08
to google-gson
I need to serialize a complex object, one of the fields of which is a
Map.

When running gson.toJson(complexObject) I get a class cast exception.
The same I receive when running the same method on the contained
map: gson.toJson(complexObject.map).

When serializing the map itself, I can use the TypeToken<Map<String,
myBean>> trick, and do the serialization.

Is there a way to run the toJson() on the complexObject and tell it to
serialize the contained map with the specific TypeToken? Do I need a
custom serializer, because I'm afraid I haven't grasped the way it
works.

Cheers,

Markos

joel....@gmail.com

unread,
Oct 9, 2008, 3:52:33 AM10/9/08
to google-gson
Does your object containing the map have type parameters defined on
the Map?

Example #1:
class Foo {
private Map<String, Bar> someMapField;
}

Example #2:
class Foo {
private Map someMapField;
}

Is your object more like example 1 or 2?

Thanks,
Joel

Markos

unread,
Oct 9, 2008, 4:00:24 AM10/9/08
to google-gson
It is like 2.

And unfortunately, I cannot change this, because it this is defined in
a separate project, which is also used in other projects that run on
Java 1.4, which does not support the first definition.

joel....@gmail.com

unread,
Oct 9, 2008, 4:22:09 AM10/9/08
to google-gson
OK, that makes sense. I think you're using an older version of Gson
because it should now throw a JsonParseException that is wrapping an
IllegalArgumentException.

Anyways, to solve your problem by copying our MapTypeAdapter and wrap
it in your own type converter. You can then take the incoming type,
which should be "Map.class" and create a ParameterizedType using new
TypeToken<Map<String, myBean>>() {}.getType(); and then delegate to
our MapTypeAdapter implementation with this type instead of Map.class.

We are considering adding the ability to serialize a Parameterized
type such as Collections without requiring the "TypeToken" thing.

Hope this information is helpful.

Joel
Reply all
Reply to author
Forward
0 new messages