7

I am trying to write a generic method for deserializing json into my model. My problem is that I don't know how to get Class from the generic type T. My code looks something like this (and doesn't compile this way)

public class JsonHelper {

    public <T> T Deserialize(String json)
    {
        Gson gson = new Gson();

        return gson.fromJson(json, Class<T>);
    }
}

I tried something else, to get the type, but it throws an error I had the class as JsonHelper<T> and then tried this

Class<T> persistentClass = (Class<T>) ((ParameterizedType)getClass()
    .getGenericSuperclass())
    .getActualTypeArguments()[0];

The method signature looks like this

com.google.gson.Gson.fromJson(String json, Class<T> classOfT)

So, how can I translate along T so that when I call JsonHelper.Deserialize<MyObject>(json); I get an instance of the correct object?

2
  • I'm not sure it's possible. If it was, why wouldn't the GSon class do it directly and remote the Class<T> parameter? Commented Feb 18, 2011 at 19:50
  • 1
    Josh, I searched for and answer to the same problem and never got one. I ended up doing what the two answers below suggest. Commented Feb 18, 2011 at 19:55

2 Answers 2

13

You need to get a Class instance from somewhere. That is, your Deserialize() method needs to take a Class<T> as a parameter, just like the underlying fromJson() method.

Your method signature should look like Gson's:

<T> T Deserialize(String json, Class<T> type) ...

Your calls will look like this:

MyObject obj = helper.Deserialize(json, MyObject.class);

By the way, the convention to start method names with a lowercase letter is well established in Java.

Sign up to request clarification or add additional context in comments.

2 Comments

I come from a background primarily in .net and that is where I picked up that coding practice. :)
@Josh: Of course it's understandable if someone coming from another language starts out using the style they're used to. That said, it's really best to learn and try to align your code style to the standards for the language you're working in.
6

Unfortunately, the way Java handles generics, you cannot get the class like you're asking. That's why Google's stuff asks specifically for the class as an argument. You'll have to modify your method signature to do the same.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.