Gson Map<String, Object> to JSon and JSON to Map

3,756 views
Skip to first unread message

heldopslippers

unread,
Mar 29, 2010, 3:06:42 AM3/29/10
to google-gson
Hi people.

I am bussy trying to get the following idea working.
For a project i am working on I am trying to parse JSON to a
Map<String, Object>.
As you all can imagine I cannot know what sort of Objects I will have
in my JSON (String?, Integer?, Long? etc..).

after some search on the internet I found the following "issue":http://
code.google.com/p/google-gson/issues/detail?id=45

For all people who do not want, can or find it bad practice to make
special classes for every "type" of json string you could get and want
to use Map's to serialize/deserialize it is very helpful..

Although after reading this "issue" I understand WHY This is not
possible out of the box with gson. I don't understand how it COULD be
done.

For example i Tried the following:
Gson gson = new Gson();
String encoded = gson.toJson(data, new TypeToken<Map<String,
Object>>() {}.getType());

This doesn't give the expected result. Can anybody tell me how this
would be possible?
I do not like the idea of defining special classes for json. I think
this is bad practice because you probably would use json for some TCP
communication between (for example servers) where you would have
databases. These databases would already have those different types
defined. When adding or removing a field in the database you would
have to change the "special" created gson classes also !! This is
bound to go horribly wrong.

Any feedback etc. would be very much appreciated!

inde...@gmail.com

unread,
Apr 27, 2010, 12:38:23 PM4/27/10
to google-gson
Gson can serialize an arbitrary map, but as you point out
deserialization is quite tricky since we dont know what type to
deserialize into. Gson does try to map the object to primitive types
(ints, floats, Strings) but anything beyond is not possible.

One option is to define your map to be a Map<String, MyType>
class MyType {
String actualType;
String json;
}

You will then write a custom deserializer for MyType. which will use
the value actionType to get a real type, and then use
Context.deserialize to get the real object that you want.

HTH
Inder
--
You received this message because you are subscribed to the Google Groups "google-gson" group.
To post to this group, send email to googl...@googlegroups.com.
To unsubscribe from this group, send email to google-gson...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/google-gson?hl=en.

Reply all
Reply to author
Forward
0 new messages