无法使用Gson api使用List反序列化对象

时间:2010-07-20 15:46:04

标签: gson

反序列化对象时出现以下异常:

com.google.gson.JsonParseException: 
  The JsonDeserializer com.google.gson.DefaultTypeAdapters$CollectionTypeAdapter@1e2befa 
    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 com.google.gson.ParameterizedTypeImpl@b565dd

以下是我尝试反序列化的类:

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;
    }
}

请指导。

1 个答案:

答案 0 :(得分:2)

如果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提供了几种机制,其中最简单的方法是在items中注释TrusRegWishAddItemEvent属性,如下所示。

class TrusRegWishAddItemEvent implements Serializable
{
  static final long serialVersionUID = 1L;

  @SerializedName("com.gsicommerce.analytics.platform.model.webstore.AnalyticsProduct")
  private final List<AnalyticsProduct> items;

  ...
}

但是没有这个@SerializedName注释,Gson在尝试反序列化时不会抛出异常,而只是构造一个TrusRegWishAddItemEvent实例,其中items为空引用。因此,目前尚不清楚在原始问题中如何生成错误消息。