-1

我正在尝试解析来自 JSON vk api wall.get 方法的响应(示例响应http://api.vk.com/method/wall.get?owner_id=100172&count=5)并且有问题

这是 JSON 结构的类

public class Wall implements Serializable {
    private static final long serialVersionUID = 1L;
    public long from_id;
    public long to_id;
    public long date; 
    public String text;
    public long id;
    public String online;

    public static Wall parse(JSONObject o) throws JSONException {
        Wall wm = new Wall();
        wm.id = o.getLong("id");
        wm.from_id = o.getLong("from_id");
        wm.to_id = o.getLong("to_id");
        wm.date = o.getLong("date");
        wm.online = o.getString("online");
        wm.text = o.getString("text");
        return wm;
    }

而且,我尝试解析 JSON 响应

protected ArrayList<Wall> parse(String source) throws JSONException{

        ArrayList<Wall> result = new ArrayList<Wall>();
        JSONObject js = new JSONObject(source);
        JSONArray response = new js.getJSONArray("items"); ///this throws exception
        for (int i=0; i< response.length(); i++){
            Wall wall = new Wall();
            JSONObject jo = response.getJSONObject(i);
            wall.from_id = jo.getLong("from_id");
            wall.id = jo.getLong("id");
            wall.to_id = jo.getLong("to_id");
            wall.date = jo.getLong("date");
            wall.online = jo.getString("online");
            wall.text = jo.getString("text");
        }
        return result;
        }
    }
4

2 回答 2

1

试试这个库,它帮助我通过 json 进行 Web 服务响应,它很容易使用:

GSON 库

使用 GSON 库的简单指南

希望这可以帮助你

于 2013-05-08T09:41:34.170 回答
0

您的 json 数组名称response不是items,请使用:

JSONArray response = new js.getJSONArray("response");

代替:

JSONArray response = new js.getJSONArray("items");

而且您没有将wall对象添加到result...

 for (int i=0; i< response.length(); i++){
        Wall wall = new Wall();
        JSONObject jo = response.getJSONObject(i);
        wall.from_id = jo.getLong("from_id");
        wall.id = jo.getLong("id");
        wall.to_id = jo.getLong("to_id");
        wall.date = jo.getLong("date");
        wall.online = jo.getString("online");
        wall.text = jo.getString("text");
        result.add(wall);
    }
于 2013-05-08T09:36:07.697 回答