java - Gson解析集合

标签 java android json gson

我有来自服务的以下 JSON 响应。

 {
    "ProductsByCategory": [
    {
    "id": 2593,
    "name": "LeJen Wrap",
    "slug": "lejen-wrap",
    "permalink": "https://shop.vivachoc.com/product/lejen-wrap/",
    "date_created": "2018-05-26T01:20:14",
    "date_created_gmt": "2018-05-26T01:20:14",
    "date_modified": "2018-05-27T13:30:25",
    "date_modified_gmt": "2018-05-27T13:30:25",
    "type": "variable",
    "status": "publish",
    "featured": false,
    "catalog_visibility": "visible",
    "description": "",
    "short_description": "",
    "sku": "",
    "price": "1",
    "regular_price": "",
    "sale_price": "",
    "date_on_sale_from": null,
    "date_on_sale_from_gmt": null,
    "date_on_sale_to": null,
    "date_on_sale_to_gmt": null,
    "price_html": "<span class=\"woocommerce-Price-amount amount\">
    ]
    }

我目前正在使用 GSON 来解析响应。这是我解析 Gson 的 java 代码。然后我使用一个集合来保存 https://github.com/google/gson/blob/master/UserGuide.md 之后的数据作为指南。

 Gson gson = new Gson();    
 Type collectionType = new TypeToken<Collection<ProductsByCategory>>(){}.getType();
 Collection<ProductsByCategory> productItems = gson.fromJson(mMessage, collectionType);

商品分类类如下:

public class ProductsByCategory {

    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("slug")
    @Expose
    private String slug;
    @SerializedName("permalink")
    @Expose
    private String permalink;
    @SerializedName("date_created")
    @Expose
    private String dateCreated;
    @SerializedName("date_created_gmt")
    @Expose
    private String dateCreatedGmt;
    @SerializedName("date_modified")
    @Expose
    private String dateModified;
    @SerializedName("date_modified_gmt")
    @Expose
    private String dateModifiedGmt;
    @SerializedName("type")
    @Expose
    private String type;
    @SerializedName("status")
    @Expose
    private String status;
    @SerializedName("featured")
    @Expose
    private Boolean featured;
    @SerializedName("catalog_visibility")
    @Expose
    private String catalogVisibility;
    @SerializedName("description")
    @Expose
    private String description;
    @SerializedName("short_description")
    @Expose
    private String shortDescription;
    @SerializedName("sku")
    @Expose
    private String sku;
    @SerializedName("price")
    @Expose
    private String price;
    @SerializedName("regular_price")
    @Expose
    private String regularPrice;
    @SerializedName("sale_price")
    @Expose
    private String salePrice;
    @SerializedName("date_on_sale_from")
    @Expose
    private Object dateOnSaleFrom;
    @SerializedName("date_on_sale_from_gmt")
    @Expose
    private Object dateOnSaleFromGmt;
    @SerializedName("date_on_sale_to")
    @Expose
    private Object dateOnSaleTo;
    @SerializedName("date_on_sale_to_gmt")
    @Expose
    private Object dateOnSaleToGmt;
    @SerializedName("price_html")
    @Expose
    private String priceHtml;
    @SerializedName("on_sale")
    @Expose
    private Boolean onSale;
    @SerializedName("purchasable")
    @Expose
    private Boolean purchasable;
    @SerializedName("total_sales")
    @Expose
    private Integer totalSales;
    @SerializedName("virtual")
    @Expose
    private Boolean virtual;
    @SerializedName("downloadable")
    @Expose
    private Boolean downloadable;
    @SerializedName("downloads")
    @Expose
    private List<Object> downloads = null;
    @SerializedName("download_limit")
    @Expose
    private Integer downloadLimit;
    @SerializedName("download_expiry")
    @Expose
    private Integer downloadExpiry;
    @SerializedName("external_url")
    @Expose
    private String externalUrl;
    @SerializedName("button_text")
    @Expose
    private String buttonText;
    @SerializedName("tax_status")
    @Expose
    private String taxStatus;
    @SerializedName("tax_class")
    @Expose
    private String taxClass;
    @SerializedName("manage_stock")
    @Expose
    private Boolean manageStock;
    @SerializedName("stock_quantity")
    @Expose
    private Object stockQuantity;
    @SerializedName("in_stock")
    @Expose
    private Boolean inStock;
    @SerializedName("backorders")
    @Expose
    private String backorders;
    @SerializedName("backorders_allowed")
    @Expose
    private Boolean backordersAllowed;
    @SerializedName("backordered")
    @Expose
    private Boolean backordered;
    @SerializedName("sold_individually")
    @Expose
    private Boolean soldIndividually;
    @SerializedName("weight")
    @Expose
    private String weight;
    @SerializedName("dimensions")
    @Expose
    private Dimensions dimensions;
    @SerializedName("shipping_required")
    @Expose
    private Boolean shippingRequired;
    @SerializedName("shipping_taxable")
    @Expose
    private Boolean shippingTaxable;
    @SerializedName("shipping_class")
    @Expose
    private String shippingClass;
    @SerializedName("shipping_class_id")
    @Expose
    private Integer shippingClassId;
    @SerializedName("reviews_allowed")
    @Expose
    private Boolean reviewsAllowed;
    @SerializedName("average_rating")
    @Expose
    private String averageRating;
    @SerializedName("rating_count")
    @Expose
    private Integer ratingCount;
    @SerializedName("related_ids")
    @Expose
    private List<Integer> relatedIds = null;
    @SerializedName("upsell_ids")
    @Expose
    private List<Object> upsellIds = null;
    @SerializedName("cross_sell_ids")
    @Expose
    private List<Object> crossSellIds = null;
    @SerializedName("parent_id")
    @Expose
    private Integer parentId;
    @SerializedName("purchase_note")
    @Expose
    private String purchaseNote;
    @SerializedName("categories")
    @Expose
    private List<Category> categories = null;
    @SerializedName("tags")
    @Expose
    private List<Object> tags = null;
    @SerializedName("images")
    @Expose
    private List<Image> images = null;
    @SerializedName("attributes")
    @Expose
    private List<Attribute> attributes = null;
    @SerializedName("default_attributes")
    @Expose
    private List<Object> defaultAttributes = null;
    @SerializedName("variations")
    @Expose
    private List<Integer> variations = null;
    @SerializedName("grouped_products")
    @Expose
    private List<Object> groupedProducts = null;
    @SerializedName("menu_order")
    @Expose
    private Integer menuOrder;
    @SerializedName("meta_data")
    @Expose
    private List<MetaDatum> metaData = null;
    @SerializedName("_links")
    @Expose
    private Links links;

但是,我不断收到以下错误

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

我没有正确遵循这个吗?我有以下包装项目的类。

public class ProductItems {

    @SerializedName("ProductsByCategory")
    @Expose
    private List<ProductsByCategory> productsByCategory = null;

    public List<ProductsByCategory> getProductsByCategory() {
        return productsByCategory;
    }

    public void setProductsByCategory(List<ProductsByCategory> productsByCategory) {
        this.productsByCategory = productsByCategory;
    }

最佳答案

此错误表明需要一个 JsonArray,但提供的 JSON 是一个 JsonObject。看看你的 JSON,在顶层你有一个名为 "ProductsByCategory"JsonObject。因此,您需要传递 JsonObject“ProductsByCategory”的内容,它是一个 JsonArray

您可以执行以下操作:

Gson gson = new Gson();    
Type collectionType = new TypeToken<Collection<ProductsByCategory>>(){}.getType();
Collection<ProductsByCategory> productItems = gson.fromJson(mMessage.getAsJsonArray("ProductsByCategory"), collectionType);

如果您已经有一个包装类(“ProductItems”),您必须按如下方式修复您的代码:

Gson gson = new Gson();    
Type collectionType = new TypeToken<ProductItems>(){}.getType();
ProductItems productItems = gson.fromJson(mMessage, collectionType);

关于java - Gson解析集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50556505/

相关文章:

java - 数据表if else语句显示

c# - 警报未访问 BroadcastReceiver

Android - 如何在设置缩放级别和标记的 Android 应用程序中启动 Google map Intent

java - 星火Java : Specify dependency jars in SparkLauncher

java - 使用拖放在 Spring 中创建表单?

android - Android Studio Linter 是否提供查找默认 XML 布局值的选项?

java - 使用 GSON 将多个 Collection<String> 合并为一个 JSON String

JQuery/MVC 搜索问题

json - 如何通过 Circe 修改 json 的值类型

java - 将 Observable<Single<Object>> 转换为 Single<List<Object>>