1

I have the following method that I am trying to use with a class that also is generic:

public static <T> T fromJson(String serializedJson, Class<T> theClazz);

And I want to deserialize a class that looks like this:

public class JsonContentWrapper<T> {
    private String version;
    private T content;
}

The way I would typically use the fromJson method is like:

JsonUtil.fromJson(someJsonString, JsonContentWrapper.class)

However, since the JsonContentWrapper has that generic object content, I'd really like to be able to do:

JsonUtil.fromJson(someJsonString, JsonContentWrapper<SomeClass>.class)

But that doesn't work. Is there a way to get a generic class and the generic it is using? I've tried something like this but didn't have much luck.

As it stands now, at least with the object I'm testing with, that T object is getting deserialized into a LinkedHashMap, which is wrong.

Community
  • 1
  • 1
Tom
  • 7,640
  • 1
  • 23
  • 47
  • Because I'm sure there has to be another way around this problem, and perhaps somebody can help with that. I don't need it to determine for me what my generic is, I'm fine with telling it: "deserialize this into this type, where T is this" – Tom Aug 26 '15 at 13:21
  • You can try and add another field in your `JsonContentWrapperClass` - `private Class contentClass`. This way you will have the particular class at runtime and you can use it to parse the content accordingly. Not sure if it is applicable in your case, though. – Danail Alexiev Aug 26 '15 at 13:28
  • You may want to take a look at gson and its `TypeToken` which can be used like `Map map2 = gson.fromJson(json, new TypeToken>() {}.getType());` – Pshemo Aug 26 '15 at 13:28

2 Answers2

2

Java implements Generics using Erasure. That means that at run-time, the JVM can't know what types are associated with the Generic class/method/object/whatever. There are hacks and workarounds that can be used to try to work with this, but this is a fundamental part of the language.

Given that you're working with JSON, you may wish to investigate whether the library has functions specialized for Generic datastructures. I happen to know for a fact that GSON has functions specific to handling Generic data structures.

Xirema
  • 19,889
  • 4
  • 32
  • 68
1

... I'm sure there has to be another way around this problem, and perhaps somebody can help with that.

Unfortunately, there isn't.

The best you can do is deserialize into JsonContentWrapper, and then do an unsafe type-cast to cast the result as JsonContentWrapper<SomeClass>.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216