3

Using Jackson we have the option to attach the type info to the serialized object (http://jackson.codehaus.org/1.5.5/javadoc/org/codehaus/jackson/annotate/JsonTypeInfo.html).

Is there a way to do this using GSON like:

{
    propertyName:"test",
    _className:"foo.bar.TestClass"
}

The idea is to have it generic, so when a ArrayList<Object> is deserialized, the right object instances are restored with it.

I saw this question: https://stackoverflow.com/a/8683689/1001027 that is more or less what I need but it works just for a specific class of objects. How could implement is in such a generic way, that every object would be serialized with this property?

Community
  • 1
  • 1
Francisco Spaeth
  • 23,493
  • 7
  • 67
  • 106

1 Answers1

0

You need to implement deserializer, which will look at the type property and cast objects to a given type. I believe, there is no other way.

Check out the javadoc, implementing this interface may be your answer.

user2256686
  • 245
  • 1
  • 7
  • I'm pretty ok with that, but the problem is the implementation needs to be generic and fall back to standard for regular types (String, int, float, double and so on) just for complex objects should be serialized with the class name, and I didn't figure out yet how to do it... please see my last sentence with the link posted. – Francisco Spaeth Apr 25 '13 at 11:37
  • @JavaMentor In any way, you're gonna need to parametrize objects in code using, for example, [DeserializationContext][1]. And in deserialize method you can check if type in JSON string matches type you've passed in code. [1]: http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/JsonDeserializationContext.html – user2256686 Apr 25 '13 at 12:38
  • this is for sure, but the question wasn't exactly this ;) – Francisco Spaeth Apr 25 '13 at 12:41
  • @JavaMentor well, looks like i didn't fully understand the question. sorry :) – user2256686 Apr 25 '13 at 12:47