2

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

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

请指导。

4

1 回答 1

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因此,不清楚在原始问题中生成错误消息的操作是什么。

于 2011-06-10T00:09:04.853 回答