com.google.gson.internal.LinkedTreeMap不能转换到我的类 [英] com.google.gson.internal.LinkedTreeMap cannot be cast to my class
问题描述
从JSON字串取得我的物件时发生问题。
I have some problems with getting my object from a JSON string.
我有产品
public class Product {
private String mBarcode;
private String mName;
private String mPrice;
public Product(String barcode, String name, String price) {
mBarcode = barcode;
mName = name;
mPrice = price;
}
public int getBarcode() {
return Integer.parseInt(mBarcode);
}
public String getName() {
return mName;
}
public double getPrice() {
return Double.parseDouble(mPrice);
}
}
从我的服务器,我得到一个 ArrayList< Product>
in JSON字符串表示形式。例如:
From my server I get an ArrayList<Product>
in JSON String representation. For example:
[{"mBarcode":"123","mName":"Apfel","mPrice":"2.7"},
{"mBarcode":"456","mName":"Pfirsich","mPrice":"1.1111"},
{"mBarcode":"89325982","mName":"Birne","mPrice":"1.5555"}]
public static <T> String arrayToString(ArrayList<T> list) {
Gson g = new Gson();
return g.toJson(list);
}
要使我的对象回来,我使用这个函数:
To get my Object back I use this function:
public static <T> ArrayList<T> stringToArray(String s) {
Gson g = new Gson();
Type listType = new TypeToken<ArrayList<T>>(){}.getType();
ArrayList<T> list = g.fromJson(s, listType);
return list;
}
但是当调用
String name = Util.stringToArray(message).get(i).getName();
我得到错误
com.google.gson.internal.LinkedTreeMap不能被投射到对象。产品
我做错了什么?看起来它创建了一个LinkedTreeMaps列表,但是如何将它转换为我的产品对象?
What am I doing wrong? It looks like it created a List of LinkedTreeMaps but how do i convert those into my Product Object?
推荐答案
为了进行类型擦除,解析器不能在运行时获取真实类型T.一种解决方法是提供类类型作为方法的参数。
In my opinion, due to type erasure, the parser can't fetch the real type T at runtime. One workaround would be to provide the class type as parameter to the method.
这样的工作原理,当然还有其他可能的解决方法,但我觉得这个很清楚简洁。
Something like this works, there are certainly other possible workarounds but I find this one very clear and concise.
public static <T> List<T> stringToArray(String s, Class<T[]> clazz) {
T[] arr = new Gson().fromJson(s, clazz);
return Arrays.asList(arr); //or return Arrays.asList(new Gson().fromJson(s, clazz)); for a one-liner
}
并像这样调用:
String name = stringToArray(message, Product[].class).get(0).getName();
这篇关于com.google.gson.internal.LinkedTreeMap不能转换到我的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!