JsonReader仅返回第一个结果

时间:2014-08-23 14:58:18

标签: android json

我正在尝试从Json文件中获取"name",因此我列出了"Group A""Group B",...但它只返回{{1} }

"Group A"

private void LoadFromJSON() { try { //JSON LOCAL InputStream input = null; try{ input = c.getResources().openRawResource(R.raw.fifa_world_cup_2014); }catch(Exception e){ e.printStackTrace(); } JsonReader reader = null; try { reader = new JsonReader(new InputStreamReader(input, "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } try { String readerName = ""; String name = ""; reader.beginArray(); reader.beginObject(); while (reader.hasNext()) { readerName = reader.nextName(); if (readerName.equals("name")) { name = reader.nextString(); } else { reader.skipValue(); } Group g = new Group(); g.setName(name); GroupDao gDAO = new GroupDao(activity); gDAO.open(); gDAO.createGroup(g); gDAO.close(); } reader.endObject(); reader.endArray(); } catch (IOException e) { e.printStackTrace(); } }catch(Exception e){ } } 档案:

Json

1 个答案:

答案 0 :(得分:0)

首先,在json字符串的最后一行将}}]更改为}]

其次,解析json的代码错误,请改用此代码

private void LoadFromJSON() {

try {

    //JSON LOCAL
    InputStream input = null;
    try{
        input = getResources().openRawResource(R.raw.fifa_world_cup_2014);
    }catch(Exception e){
        e.printStackTrace();
    }
    JsonReader reader = null;
    try {
        reader = new JsonReader(new InputStreamReader(input, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }


    try {
        String readerName = ""; 
        String name = "";

        reader.beginArray();
        while (reader.hasNext()) {
            reader.beginObject();
            while(reader.hasNext())
            {
                readerName = reader.nextName();
                if (readerName.equals("name")) {
                     name = reader.nextString();
                     Group g = new Group();
                     g.setName(name);
                     GroupDao gDAO = new GroupDao(activity);
                     gDAO.open();
                     gDAO.createGroup(g);
                     gDAO.close();
                } else {
                     reader.skipValue();
                }

            }
            reader.endObject();
        }
        reader.endArray();

    } catch (IOException e) {
        e.printStackTrace();
    }

}catch(Exception e){

}
}

我测试了代码,工作正常并解析了A组和B组。

此致