【发布时间】:2015-01-30 22:38:58
【问题描述】:
我在从 JSON 字符串中获取对象时遇到了一些问题。
我上课了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> String arrayToString(ArrayList<T> list) {
Gson g = new Gson();
return g.toJson(list);
}
为了找回我的对象,我使用了这个函数:
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 列表,但我如何将它们转换为我的产品对象?
【问题讨论】:
-
试试这个 -keepattributes 签名
-
您可以遍历
ArrayList以将每个LinkedTreeMap项目转换为Product项目。您可以再次使用Gson进行转换。在此处查看示例代码:randomgyan.com/…