Gson type marker issue with general deserialization

I found many similar questions, but none of them helped.

It works:

public class Assets<T> { public T getAndDeserializeAsset(String endpoint, String assetId, Client client){ Response response = client.get(endpoint+assetId); Gson gson = new Gson(); T asset = gson.fromJson(response.body, new TypeToken<Email>(){}.getType()); return asset; } 

}

It does not mean:

 public class Assets<T> { public T getAndDeserializeAsset(String endpoint, String assetId, Client client){ Response response = client.get(endpoint+assetId); Gson gson = new Gson(); T asset = gson.fromJson(response.body, new TypeToken<T>(){}.getType()); return asset; } 

}

I did this according to the official documentation, so I have no idea why this is not working.

Error:

 Exception in thread "main" java.lang.ClassCastException: com.rest.api.Response cannot be cast to model.Email at main.Main.main(Main.java:34) 
+6
source share
2 answers

The only thing that makes sense is that your instance of Assets<T> should be an instance of Assets<Response> , not Assets<Email> . Are you absolutely sure your Assets instance is the right type?

Also, remember that Gson is not covariant ; when you specify a type using TypeToken , you must use the exact type you want to deserialize. For example, if you use a class definition:

 class Email extends Response { 

and then use:

 new Assets<Response>(); 

Since Gson is not covariant, there is no way to know that you really want Email .

0
source

The above code cannot interpret the value as a type because Gson calls Assets.getClass () to get information about its class, but this method returns the class raw, Assets.class. This means that Gson does not know that it is an object of type Assets <Example> and not just simple assets.

You can solve this problem by specifying the correct parameterized type for your generic type. You can do this using the TypeToken class.

 Type AssetsType = new TypeToken<Assets<Example>>() {}.getType(); gson.toJson(assets, AssetsType ); gson.fromJson(json, AssetsType ); 

for more info check gson-user-guide

0
source

Source: https://habr.com/ru/post/986671/


All Articles