1

I am trying to abstract the code in my previous post into a util class. Here's the util class method:

private static Gson gson = new GsonBuilder().create();

public static Class getResponseObject(String resourceResponse, String jsonObject, Class responseClass) {
    JSONObject jsonResponse = new JSONObject(resourceResponse);
    String jsonResponseToString = jsonResponse.getJSONObject(jsonObject).toString();
    return gson.fromJson(jsonResponseToString, responseClass.getClass());
}

And this is the call from another class:

UserIdentifier userIdentifier = ServiceClientUtil.getResponseObject(resourceResponse,
                                                                    "userIdentifier",
                                                                    UserIdentifier.class);

But I'm getting the following error:

Error:(68, 76) java: incompatible types: java.lang.Class cannot be converted to app.identity.UserIdentifier

How do I pass in a class object and return the same class object?

1
  • That error message is clear enough. What do you not understand about it? Commented Feb 4, 2016 at 22:37

1 Answer 1

4

I think in this scenario you actually want to use something other than Class. Be careful though: it only makes sense to serialize key-value pairs (or an object representation of such) into a JSON value, since a raw Integer is not valid JSON.

What we can do is change the signature of your method to take in any object, and since Class can be typed, that becomes easier to do.

The signature of your method would be (untested):

public static <T> T getResponseObject(String resourceResponse,
                                      String jsonObject,
                                      Class<T> responseClass)

This way, we can ensure that the type we pass to this method is an instance of what we get. Remember: I'm not guaranteeing that this approach will work for flat values such as Integers, but it should ideally work for any other custom object that you create.

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

3 Comments

no this is not what i want because i am trying to make this a reusable method. So i want to be able to pass in any type of class for the responseClass and get that returned. For example, I should be able to pass in Integer.class and get that returned. I was just using the UserIdentifier as an example
@Richard: I don't think Integer is going to work the way you want it to work but I've revised my answer.
perfect, this worked exactly like i wanted. Thank you

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.