1

I know it's a frequently asked question, but after searching for two hours I'm asking here if there's a solution. I need to implement a third party interface that serializes and deserializes objects in an Android app. I'd like to use Gson to achieve this. The methods are the following:

@Override
public byte[] serialize(Object object) throws IOException {
    return new Gson().toJson(object).getBytes();
}

@Override
public <T extends Job> T deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
    // problem here
}

I can't use something like this:

gson.fromJson(responseBody, new TypeToken<T>() {}.getType());

Because it returns an object of type LinkedTreeMap. Gson needs the Class of the object, but I've only this T (I come from the .net world, where generics are more "developer friendly").

Is it possible to obtain the original class of T in this scenario?

durron597
  • 31,968
  • 17
  • 99
  • 158
Carlo G
  • 442
  • 7
  • 15
  • Unlikely. What you could do is have the `TypeToken` be another argument to `deserialize` and force the caller of `deserialize` to declare what type they expect. Otherwise, no, you can't deserialize an object of an unknown type with Gson. – Louis Wasserman Sep 02 '15 at 20:49
  • I see. Unfortunately I can't change neither the method signature nor the caller. Thanks anyway. – Carlo G Sep 02 '15 at 20:56
  • 1
    Then you're...pretty much SOL. You'll need to be specific for which object type you expect. – Louis Wasserman Sep 02 '15 at 20:56

1 Answers1

1

As you've already discussed in the comments, it's not possible for Gson to be really brilliant and figure out what the original object was. If you spend 5 minutes thinking about how that would have to work, you'll realize it's impossible.

However, you might be able to, in a custom deserializer, analyze the Json and figure out what type it was supposed to be. Gson already has RuntimeTypeAdapterFactory for this. See this discussion for a working example: https://stackoverflow.com/a/22081826/1768232

Basically, you can use this factory to specify the type in the json itself, (it will look like "type":"typename", which will make it possible for you to do the deserialization.

If modifying the json is not an option, you can still write a custom deserializer to analyze the json and attempt to figure out what type it's supposed to be, but that logic is much more difficult.

Community
  • 1
  • 1
durron597
  • 31,968
  • 17
  • 99
  • 158