Java google gson LinkedTreeMap 类转换为 myclass
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32444863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
google gson LinkedTreeMap class cast to myclass
提问by EngineSense
I knew this question has been asked before. Due to my novice skill in java and android. I can't resolve this issue for more than a week.
我知道以前有人问过这个问题。由于我在java和android方面的新手技能。我无法解决这个问题超过一个星期。
One of my friend and i developing an android project were there are a couple of things like this.
我和我的一个朋友正在开发一个 android 项目,有几件这样的事情。
The most weird part of this things is, it's happening only from when i download and test it from Google play store. Not from local android studio installation or debug mode.
这件事最奇怪的部分是,只有当我从 Google Play 商店下载并测试它时才会发生这种情况。不是来自本地 android studio 安装或调试模式。
What could be the problem here, or this returning list which is totally wrong ? My friend convincing that this code returns correctly but from play store installation it's always an error.
这里可能有什么问题,或者这个返回列表是完全错误的?我的朋友确信此代码返回正确,但从 Play 商店安装它总是一个错误。
Please suggest me where should i keep digging?
请建议我应该在哪里继续挖掘?
@Override
public void promiseMethod(JSONObject object) {
if (object != null) {
if (object.has(DO_SERVICES)) {
vehicleDetails = new ArrayList < Object[] > (1);
List < String > vehicleNoList = new ArrayList < String > (1);
List < String > serviceList = new ArrayList < String > (1);
try {
Gson gson = new Gson();
JSONObject jsonObj = new JSONObject(object.get(DO_SERVICES)
.toString());
servDto = gson.fromJson(jsonObj.toString(),
ServiceDto.class);
if (servDto.getServiceDto() instanceof List) {
List < DoServiceDto > doServiceList = servDto.getServiceDto();
Exception is
例外是
java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to com.gaurage.dto.DoServiceDto at com.gaurage.user.User_Test_Main.promiseMethod(Unknown Source)
java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap 无法在 com.gaurage.user.User_Test_Main.promiseMethod(Unknown Source) 上转换为 com.gaurage.dto.DoServiceDto
采纳答案by EngineSense
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:
当您调用 toJson(obj) 时,Gson 会调用 obj.getClass() 以获取有关要序列化的字段的信息。同样,您通常可以在 fromJson(json, MyClass.class) 方法中传递 MyClass.class 对象。如果对象是非泛型类型,这可以正常工作。但是,如果对象是泛型类型,那么由于 Java 类型擦除,泛型类型信息将丢失。这是一个说明这一点的例子:
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.
上面的代码无法将 value 解释为 Bar 类型,因为 Gson 调用 list.getClass() 来获取其类信息,但此方法返回一个原始类 Foo.class。这意味着 Gson 无法知道这是一个 Foo 类型的对象,而不仅仅是普通的 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.
您可以通过为泛型类型指定正确的参数化类型来解决此问题。您可以通过使用 TypeToken 类来做到这一点。
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.
我有父类,它是子类,其中一些包含 List 类型。像这个父类一样,我有 30 个文件。我是这样解决的。
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.
最重要的是,我无法在 Android Studio 的本地测试中重现此错误。此问题仅弹出,当我生成签名的 apk 并将应用程序发布到 PlayStore 时应用程序停止,并且报告显示无法将 LinkedTreeMap 转换为 myclass。
It was hard for me to reproduce the same result in my local testing (includes Debug mode).
我很难在本地测试(包括调试模式)中重现相同的结果。
回答by Code Spy
In My ListView BaseAdapterfacing same issue
在我的ListView BaseAdapter面临同样的问题
JSON formatto show
要显示的JSON 格式
{
results: [
{
id: "10",
phone: "+91783XXXX345",
name: "Mr Example",
email: "[email protected]"
},
{
id: "11",
phone: "+9178XXXX66",
name: "Mr Foo",
email: "[email protected]"
}],
statusCode: "1",
count: "2"
}
I was facing this issue
我正面临这个问题
E/AndroidRuntime: FATAL EXCEPTION: main Process: com.hsa.ffgp.hapdfgdfgoon, PID: 25879 java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to com.hsa.......
E/AndroidRuntime: FATAL EXCEPTION: main Process: com.hsa.ffgp.hapdfgdfgoon, PID: 25879 java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap 不能转换为 com.hsa ......
Then I mapped data using LinkedTreeMapKey Value as below
然后我使用LinkedTreeMapKey Value映射数据,如下所示
...
...
@Override
public View getView(final int i, View view, ViewGroup viewGroup) {
if(view==null)
{
view= LayoutInflater.from(c).inflate(R.layout.listview_manage_clients,viewGroup,false);
}
TextView mUserName = (TextView) view.findViewById(R.id.userName);
TextView mUserPhone = (TextView) view.findViewById(R.id.userPhone);
Object getrow = this.users.get(i);
LinkedTreeMap<Object,Object> t = (LinkedTreeMap) getrow;
String name = t.get("name").toString();
mUserName.setText("Name is "+name);
mUserPhone.setText("Phone is "+phone);
return view;
}
...
...
回答by Deepak Kataria
In my case error occurred while fetching a list of objects from shared preferences. The error was solved by adding TypeToken as shown below:
在我的情况下,从共享首选项中获取对象列表时发生错误。通过添加 TypeToken 解决了错误,如下所示:
public static <GenericClass> GenericClass getListOfObjectsFromSharedPref(Context context,String preferenceFileName, String preferenceKey ){
SharedPreferences sharedPreferences =
context.getSharedPreferences(preferenceFileName, 0);
Type type = new TypeToken<ArrayList<Classname.class>>() {}.getType();
String json = sharedPreferences.getString(preferenceKey, "");
final Gson gson = new Gson();
return gson.fromJson(json, type);
}
....
....