我从使用JSON字符串获取对象时遇到了一些问题。com.google.gson.internal.LinkedTreeMap无法投射到我的课堂
我得到了类Product
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);
}
}
从我的服务器我在JSON字符串表示得到一个ArrayList<Product>
。例如:
[{"mBarcode":"123","mName":"Apfel","mPrice":"2.7"},
{"mBarcode":"456","mName":"Pfirsich","mPrice":"1.1111"},
{"mBarcode":"89325982","mName":"Birne","mPrice":"1.5555"}]
此字符串是这样产生的:
为了让我的对象后,我用这个函数:
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不能转换为object.Product
我在做什么错了?它看起来像创建了LinkedTreeMaps列表,但我如何将它们转换为我的产品对象?
这个答案提供了一个解决办法,但是没有解决嵌套泛型的问题。请参阅这两个答案以获得更一般的解决方案: http://stackoverflow.com/a/14506181/4745878 http://stackoverflow.com/a/26203635/4745878 – 2016-04-01 21:26:20
此解决方法比真正的解决方案更好。谢谢亚历克西斯C. – pcejrowski 2016-11-13 18:54:46