-1

在线上

reader.beginArray();

我得到错误:

expected beginarray but was beginobject. 

我尝试更改.beginArray()为,.beginObject()但它不起作用。

此代码是JsonParser

public List<Noticias> leerArrayNoticias(JsonReader reader) throws IOException {
    ArrayList<Noticias> noticias = new ArrayList<>();
    try {
        reader.beginArray();
        while (reader.hasNext()) {

            noticias.add(leerNoticia(reader));
        }
        reader.endArray();
    }catch(IOException e){
        e.printStackTrace();
    }catch(Exception e){
        e.printStackTrace();
    }
    return noticias;
}

这是我试图解析的 Json

{"noticias":
    [    
        {"idnoticias":"109","titulo":"nueva1","descripcion":"nuevo1"},
        {"idnoticias":"110","titulo":"nueva2","descripcion":"nuevo2"}
    ]
}
4

1 回答 1

0

你读错了 JSON,因为这个 JSON 包含一个 JSON 对象,然后是一个带有 key 的 JSON-Array "noticias"。所以我们必须像这样读取 JSON:

public void readNotes (final JsonReader reader) {
    // MARKING THE FOLLOWING FOR DELETION (SEE BELOW)
    reader.beginObject(); // First start reading the object
    reader.nextName(); // Read the noticias key, we don't need the actual key
    // END MARKING 
    reader.beginArray(); // Start the array of objects

    while (reader.hasNext()) {
        // Start the object and read it out
        reader.beginObject();

        reader.nextName();
        final int idnotes = reader.nextInt();

        reader.nextName();
        final String title = reader.nextString();

        reader.nextName();
        final String description = reader.nextString();

        // Do stuff with the variables

        // Close this object
        reader.endObject();
    }

    reader.endArray(); // Close the array

    // MARKING THE FOLLOWING FOR DELETION (SEE BELOW)
    reader.endObject(); // Close the object
    // END MARKING 
}

但是,您的 JSON 可以优化,因为我们不需要第一个对象。那么 JSON 会是这样的:

[    
    {"idnoticias":"109","titulo":"nueva1","descripcion":"nuevo1"},
    {"idnoticias":"110","titulo":"nueva2","descripcion":"nuevo2"}
]

如果您有此 JSON,则可以省略上面标记的规则以使其正常工作。

于 2015-08-17T20:11:23.113 回答