具有相同标题名称的Json Parsing会生成Error

时间:2014-10-19 12:42:15

标签: android json gson

我有一个json,其中有产品和类别。关键字产品也属于类别。 json

{
"categories": [
    {
        "id": "categoryA",
        "name": "Coffees",
        "products": [
            "productA",
            "productC",
            "productE",
            "productF"
        ]
    },
    {
        "id": "categoryB",
        "name": "Extra Coffees",
        "products": [
            "productB",
            "productG",
            "productA"
        ]
    },
    {
        "id": "categoryC",
        "name": "Small Coffees",
        "products": [
            "productA",
            "productG",
            "productE"
        ]
    }
],
"products": [
    {
        "id": "productA",
        "name": "Coffe A",
        "price": 350
    },
    {
        "id": "productB",
        "name": "Coffe B",
        "price": 450
    },
    {
        "id": "productC",
        "name": "Coffe C",
        "price": 150
    },
    {
        "id": "productD",
        "name": "Coffe D",
        "price": 250
    },
    {
        "id": "productE",
        "name": "Coffe E",
        "price": 500
    },
    {
        "id": "productF",
        "name": "Coffe F",
        "price": 325
    },
    {
        "id": "productG",
        "name": "Coffe G",
        "price": 315
    },
    {
        "id": "productH",
        "name": "Coffe H",
        "price": 350
    }
]}

我为Product和Categories创建了以下两个类。

分类

public class Categories {
    private String id;
    private String name;
    private ArrayList<String> products;

    public String getId() {
        return this.id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

产品

public class Products {
    private String id;
    private String name;
    private double price = 0;

    public String getId() {
        return this.id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return this.price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}

现在我创建了另一个用于从Json解析到Entity的类。那个班是:

public class CategoriesProducts {
    private ArrayList<Categories> categories;
    private ArrayList<Products> products;
}

当我尝试解析时出现错误:Expected a string but was BEGIN_OBJECT at line 1 column 299. 我正在通过以下代码行解析json。

Categories cat = GsonFactory.getConfiguredGson().fromJson(abc , Categories.class);

谁能告诉我我做错了什么?

1 个答案:

答案 0 :(得分:2)

这应该有效:

CategoriesProducts catProd = GsonFactory.getConfiguredGson().fromJson(abc, CategoriesProducts.class);

abc是包含JSON的String