google gson LinkedTreeMap class cast to myclass
Serializing and Deserializing Generic Types
When you call toJson(obj), Gson calls obj.getClass() to get information on the fields to serialize. Similarly, you can typically pass MyClass.class object in the fromJson(json, MyClass.class) method. This works fine if the object is a non-generic type. However, if the object is of a generic type, then the Generic type information is lost because of Java Type Erasure. Here is an example illustrating the point:
class Foo<T> { T value;}
Gson gson = new Gson();
Foo<Bar> foo = new Foo<Bar>();
gson.toJson(foo); // May not serialize foo.value correctly
gson.fromJson(json, foo.getClass()); // Fails to deserialize foo.value as Bar
The above code fails to interpret value as type Bar because Gson invokes list.getClass() to get its class information, but this method returns a raw class, Foo.class. This means that Gson has no way of knowing that this is an object of type Foo, and not just plain Foo.
You can solve this problem by specifying the correct parameterized type for your generic type. You can do this by using the TypeToken class.
Type fooType = new TypeToken<Foo<Bar>>() {}.getType();
gson.toJson(foo, fooType);
gson.fromJson(json, fooType);
I have Parent class and it's child class some of them having List types in it. Like this parent class i have 30 files. I solved it like this.
Gson gson = new Gson();
JSONObject jsonObj = new JSONObject(object.get(DO_SERVICES).toString());
Type type = new TypeToken<MyDto>() {}.getType();
servDto = gson.fromJson(jsonObj.toString(),type);
The most important thing is, I can't reproduce this error in local testing from Android studio. This problem pops up only, When i generate signed apk and publish app into PlayStore were the app stops, and the report says Cannot cast LinkedTreeMap to myclass.
It was hard for me to reproduce the same result in my local testing (includes Debug mode).
class com.google.gson.internal.LinkedTreeMap cannot be cast to class Return
This is caused by type erasure on the JVM: at runtime, the function getObject
doesn't know what type T is. You need to make it an inline function and use a reified type. Change it as follows and it should work:
inline fun <reified T> getObject(url: String): T {
... leave body as before
}
class com.google.gson.internal.LinkedTreeMap cannot be cast to class Partner
It is due to type erasure in runtime. In Kotlin you can solve this issue by making your function inline with reified
type:
Change your function from:
fun <T> fromJson(json: String?): T {
return Gson().fromJson<T>(json, object: TypeToken<T>(){}.type)
}
To:
inline fun <reified T> fromJson(json: String?): T {
return Gson().fromJson<T>(json, object: TypeToken<T>(){}.type)
}
For further reading check this out: https://kotlinlang.org/docs/reference/inline-functions.html
com.google.gson.internal.LinkedTreeMap cannot be cast
You are using ArrayList<ListPojo>
so you need to make sure that the parsing should happen using right type List<ListPojo>
instead of list
which has no type
due to the missing type information , gson
is returning a List
of internally
created objects LinkedTreeMap
and since you are using raw
types (should be a warning for unchecked cast)with declaration as concrete type which will create a issue when adapter actually expecting a PojoObject
but internally it's something else. so solution
Never use raw-types anywhere possible
so do
public interface CountryArrayAPI {
@GET("api/popular_destinations")
public Call<List<ListPojo>> getCountries();
}
and also remove /
before api
and call will be like
call.enqueue(new Callback<List<ListPojo>>() {
@Override
public void onResponse(Call<List<ListPojo>> call, Response<List<ListPojo>> response) {
listPojos = response.body();
and always code to interface
so
List<ListPojo> listPojos = ...;
How to deal with cannot be cast to class error - GSON JAVA
public List<Medicine> FromJsonToArray() throws IOException {
String medicineJson = initArray("Medicines.json").toString();
Gson gson = new Gson();
Type medicineListType = new TypeToken<List<Medicine>>() {}.getType();
List<Medicine> medicineArray = gson.fromJson(medicineJson, medicineListType);
return medicineArray;
}
should do the trick.
Basically it is a workaround to tell gson to deserialize to a list of particular class.
That is required because generics are lost at runtime and your json was being deserialized to List<LinkedTreeMap>
instead of List<Medicine>
.
Related Topics
Android Gives Error "Cannot Fit Requested Classes in a Single Dex File"
Tm.Getdeviceid() Is Deprecated
Google Signin API Exception 10
How to Fix Install_Parse_Failed_Manifest_Malformed in My Android Application
Android Debugging Inetaddress.Isreachable
How to Get Java Output with Ruby
How to Convert Between Iso-8859-1 and Utf-8 in Java
How to Create My Own Appender in Log4J
Preload Multiple Images with Glide
Noclassdeffounderror on External Library Project for Android
Adding Header to All Request with Retrofit 2
How Many Ways to Convert Bitmap to String and Vice-Versa
Binary Xml File Line #0: Error Inflating Class Imageview
What Is the Correct Way to Do Inserts/Updates/Deletes in Android SQLitedatabase Using a Query String
Why Ruby Modulo Is Different from Java/Other Lang
Spark: How to Map Python with Scala or Java User Defined Functions