Home > OS >  how to use gson.fromJson with generic type T
how to use gson.fromJson with generic type T

Time:09-21

I am trying to build a generic method which will call any of an APIs specific endpoints, each of which returns its own object type.

private  <T> T callApi(String endpoint) {
  T responseSuccessObject = null;
  String responseBody = ...
  responseSuccessObject = (T) gson.fromJson(responseBody, responseSuccessObject.getClass());
}

The above does not work (fails with null pointer exception)

Also tried this:

private  <T> T callApi(String endpoint) {
  T responseSuccessObject = (T) new Object();
  String responseBody = ...
  responseSuccessObject = (T) gson.fromJson(responseBody, responseSuccessObject.getClass());
}

Which fails with this:

com.xx.AuthResponseModel is in unnamed module of loader org.apache.felix.framework.BundleWiringImpl$BundleClassLoader @58bd8c78)

I have seen a possible solution by passing in a dummy object of the required class, but this is not an ideal option, as it would require adding and passing the type parameter down a long line of calls.

Not sure how this would work.

private  <T> T callApi(Class<T> type, String endpoint) {
  T responseSuccessObject = null;
  String responseBody = ...
  responseSuccessObject = (T) gson.fromJson(responseBody, ?);
}

CodePudding user response:

What you're looking for is just

private  <T> T callApi(Class<T> type, String endpoint) {
  T responseSuccessObject = null;
  String responseBody = ...
  responseSuccessObject = (T) gson.fromJson(responseBody, type);
}

If there were a solution that avoided passing along the Class object, Gson would already use it. There isn't. To learn more, research type erasure.

  • Related