无法使用GSON API
问题描述:
收到以下异常反序列化对象进行反序列化对象与列表:无法使用GSON API
com.google.gson.JsonParseException:
The JsonDeserializer [email protected]a
failed to deserialized json object
{"com.gsicommerce.analytics.platform.model.webstore.AnalyticsProduct":
[
{"id":"3680231","longTitle":"Graco SnugRide Infant Car Seat - Pippin","available":"true"}
]
}
given the type [email protected]
这里是我试图反序列化类:
public class TrusRegWishAddItemEvent implements Serializable {
static final long serialVersionUID = 1L;
private final List<AnalyticsProduct> items;
private TrusRegWishAddItemEvent() {
items = null;
}
public TrusRegWishAddItemEvent(List<AnalyticsProduct> items) {
this.items = items;
}
public List<AnalyticsProduct> getItems() {
return items;
}
}
public class AnalyticsProduct implements Serializable {
static final long serialVersionUID = 1L;
private final long id;
private final String longTitle;
private final boolean available;
public AnalyticsProduct() {
id = 0;
longTitle = null;
available = false;
}
public AnalyticsProduct(long id, String longTitle, boolean available) {
this.id = id;
this.longTitle = longTitle;
this.available = available;
}
public long getId() {
return id;
}
public String getLongTitle() {
return longTitle;
}
public boolean isAvailable() {
return available;
}
}
请指南。
答
如果JSON是
{
"items":
[
{
"id":"3680231",
"longTitle":"Graco SnugRide Infant Car Seat - Pippin",
"available":"true"
}
]
}
然后将下面的示例使用GSON容易地反序列化/序列化到/从原来的问题相同的Java数据结构。
public static void main(String[] args) throws Exception
{
Gson gson = new Gson();
TrusRegWishAddItemEvent thing = gson.fromJson(new FileReader("input.json"), TrusRegWishAddItemEvent.class);
System.out.println(gson.toJson(thing));
}
相反,如果JSON必须
{"com.gsicommerce.analytics.platform.model.webstore.AnalyticsProduct":
[
{"id":"3680231","longTitle":"Graco SnugRide Infant Car Seat - Pippin","available":"true"}
]
}
然后有必要的JSON元素名称"com.gsicommerce.analytics.platform.model.webstore.AnalyticsProduct"
转换为Java成员items
。为此,Gson提供了一些机制,其中最简单的方法就是如下注释TrusRegWishAddItemEvent
中的items
属性。
class TrusRegWishAddItemEvent implements Serializable
{
static final long serialVersionUID = 1L;
@SerializedName("com.gsicommerce.analytics.platform.model.webstore.AnalyticsProduct")
private final List<AnalyticsProduct> items;
...
}
但是,如果没有这@SerializedName
注释试图反序列化时GSON不抛出一个异常,而是它只是构建与items
为空引用一个TrusRegWishAddItemEvent
实例。所以,目前还不清楚在原始问题中如何生成错误消息。
您是否找到解决此问题的解决方案? – zohar 2013-09-11 15:31:00