yfpayalan
yfpayalan

Reputation: 43

GSON could not convert generic <T> attribute

i currently use Google's GSON library to serialize/deserialize rest service responses. But i have a little problem. My response object has T response attribute.

public class IninalResponse<T> {

    private int httpCode;
    private String description;
    private T response;
    private HashMap<String,String> validationErrors;

    ...
}

I would like to get response attribute according to object type which i specified. At this example i specified with GetAccessTokenResponse to deserialize T response attribute in the piece of code below.

public IninalResponse getAccessToken(String apikey) {
    String path = "https://sandbox-api.ininal.com/v2/oauth/accesstoken";
    return doPostIninal(apikey,path,null,GetAccessTokenResponse.class);
}

GSON library successfully deserializes IninalResponse object except for T response field. Gson deserializes it as LinkedTreeMap typed object.

public <T,V> IninalResponse doPostIninal(String apikey, String path,V requestBody, T response) {
    RestTemplate template = restClient.getRestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.AUTHORIZATION,apikey);
    headers.add(HttpHeaders.DATE, "");
    headers.add(HttpHeaders.CONTENT_TYPE, "application/json");

    HttpEntity<?> request = new HttpEntity<Object>(requestBody,headers);
    ResponseEntity<String> accessTokenResponse = restClient.getRestTemplate().postForEntity(path,request,String.class);

    IninalResponse<T> responseBody = new IninalResponse<T>();
    responseBody = new Gson().fromJson(accessTokenResponse.getBody(),responseBody.getClass());
    System.out.println(accessTokenResponse);
    return responseBody;
}

Still i have no idea why gson could not deserialize ? What exactly am i missing ?

Upvotes: 0

Views: 103

Answers (1)

user6367252
user6367252

Reputation:

Due to Java's type erasure, you need to make a trick to serialize/deserialize generic types:

Type fooType = new TypeToken<IninalResponse<TheType>>() {}.getType();    
gson.fromJson(accessTokenResponse.getBody(), fooType);

where TheType is the type you passed in during serialization (String I suppose).

Serialization goes as this:

Type fooType = new TypeToken<IninalResponse<String>>() {}.getType(); // I assume it was a String here.    
gson.toJson(someString, fooType);

Upvotes: 1

Related Questions