使用GSON从此Json字符串中提取对象

时间:2014-04-02 15:34:17

标签: java android json gson

我需要为这个json字符串获取一个Works数组:

  [
        {
            "worktypes": [
                {
                    "works": [
                        {
                            "price": "22,22",
                            "code": "A00011",
                            "name": "name 2"
                        },
                        {
                            "price": "22,22",
                            "code": "A00011",
                            "name": "name 3"
                        },
                        {
                            "price": "22,22",
                            "code": "A00011",
                            "name": "name 4"
                        },
                        {
                            "price": "11",
                            "name": "aa",
                            "code": "aa"
                        },
                        {
                            "price": "12,22",
                            "name": "Nombre",
                            "code": "A00112"
                        },
                        {
                            "price": "22",
                            "name": "asdads",
                            "code": "asdasd"
                        },
                        {
                            "price": "11",
                            "name": "yy",
                            "code": "yy"
                        }
                    ],
                    "name": "Pompas"
                }
            ]
        }
    ]

我试试这个:

List<Work> works = gson.fromJson(value.toString(), new TypeToken<List<Work>>() {}.getType());

但是没有人......怎么了?

PD:工作是一个包含价格,代码和名称值的类。

1 个答案:

答案 0 :(得分:0)

让另一个类成为WorkTypes.class,并拥有一个Work对象的ArrayList实例。

public class WorkTypes  {

    //worktypes here should match json...character to character!
    private ArrayList<Work> worktypes;

    public ArrayList<Work> getEntities() {
        return worktypes;
    }

    public void setEntities(ArrayList<Work> worktypes) {
        this.worktypes = worktypes;
    }
}

然后对于GSON,做类似的事情:

    WorkTypes objs = null;
    objs = gson.fromJson(jsonDataString, WorkTypes.class);