如何在android中使用gson库解析JSON数据

时间:2016-05-18 18:24:56

标签: android gson

来自网址

的回复
[{
  "name": "Bread Bakery & Dairy Product",
  "url": "/images/bread.jpg",
  "id": "5"
}, {
  "name": "Baby Care",
  "url": "/images/baby.jpg",
  "id": "2"
}, {
  "name": "Beverages",
  "url": "/beverages.jpg",
  "id": "6"
}, {
  "name": "Breakfast",
  "url": "/breakfast.jpg",
  "id": "1"
}, {
  "name": "Cleaning",
  "url": "/cleaning.jpg",
  "id": "3"
}, {
  "name": "Kitchen",
  "url": "/images/kitchen.jpg",
  "id": "7"
}, {
  "name": "Others",
  "url": "/images/others.jpg",
  "id": "9"
}, {
  "name": "Personal Care",
  "url": "/images/personal_care.jpg",
  "id": "8"
}, {
  "name": "Snacks",
  "url": "/images/snacks.jpg",
  "id": "4"

}]

SuperCategory.java

public class SuperCategory {

    private int id;
    private String name;
    private String url;

    public SuperCategory() {
    }

    public SuperCategory(int id, String name, String url) {
        this.id = id;
        this.name = name;
        this.url = url;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}

这是我使用gson解析JSOn的逻辑。

List<SuperCategory> superCategories = new ArrayList<>();
GsonBuilder builder = new GsonBuilder();
Gson mGson = builder.create();
superCategories = Arrays.asList(mGson.fromJson(response.toString(), SuperCategory[].class));

But it is giving size 0 for superCategories.size().

有人可以帮我解析一下有什么问题吗?

1 个答案:

答案 0 :(得分:1)

尝试从

更改代码

GsonBuilder builder = new GsonBuilder(); Gson mGson = builder.create();

变得像这样

Gson mGson = new Gson();