Wrap certain values when serializing JSON with Gson

308 views
Skip to first unread message

Josh

unread,
Apr 5, 2012, 11:36:43 AM4/5/12
to googl...@googlegroups.com

How can I wrap certain values when serializing an object model to JSON with GSON? Example model:

class Order {
 
Customer cust;
}

class Customer {
 
String name;
 
int age;
}

Serializing a Customer would normally yield something like:

{cust:{name:joe, age:21}}

What I would like to do is wrap the Order and Customer values in an additional element with the class name. So the expected JSON would be:

{Order:{cust:Customer:{name:joe, age:21}}}

The actual classes that I'll be serializing could be anything, so I can't hardcode specific properties in a serializer. But I will want to wrap certain properties with their class name. How can I do this?

Thanks,

Josh

Inderjeet Singh

unread,
Apr 5, 2012, 1:58:45 PM4/5/12
to googl...@googlegroups.com
The output that you have is NOT valid JSON.

I think another approach would be serialize an additional field called className with each JsonObject.
You would have to write a custom serializer for it. 

In general, I think it is a bad idea if you send class name in JSON as it makes your JSON only meaningful to Java endpoints.
Another approach would be to add a "type" field that uses some enum values to identify the type of the object being sent.

HTH
Inder

Josh

unread,
Apr 5, 2012, 2:24:31 PM4/5/12
to googl...@googlegroups.com
Thanks for the response Inder.

Unfortunately I don't have access to add fields to the objects I'm serializing. They're closed to me.

I'm actually not sending the class name, I'm sending the simple class name, and even then only if an annotation specifying some other type key isn't present. The class name or annotation is just a way of tying some "key" to some type, so I know what type to deserialize the JSON to when received later.

I think the idea works fine, but where to put key in the document? Wrapping a document that requires a type key in another element works conceptually (and in Jackson, but I won't go there right now). I'm not sure how to get it to work in Gson though. Any suggestions or workable alternatives are appreciated.

Thanks,
Josh

Jesse Wilson

unread,
Apr 6, 2012, 11:47:01 AM4/6/12
to google-gson
You might be able to accomplish what you want with
RuntimeTypeAdapterFactory. That class _isn't_ in the gson.jar, so
you'll need to copy it into your own project manually.
http://code.google.com/p/google-gson/source/browse/trunk/extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java

Josh

unread,
Apr 6, 2012, 11:58:15 AM4/6/12
to googl...@googlegroups.com
Very nice - this is exactly the sort of thing I wanted to accomplish. Thanks for sharing.

If you don't mind my drawing some attention to my one other blocking issue right now, I posted about it in a separate thread:


Thanks,
Josh
Reply all
Reply to author
Forward
0 new messages