Java 应为BEGIN\u数组,但为BEGIN\u对象解析JSON
排队Java 应为BEGIN\u数组,但为BEGIN\u对象解析JSON,java,android,arrays,reader,Java,Android,Arrays,Reader,排队 reader.beginArray(); 我得到一个错误: expected beginarray but was beginobject. 我尝试将.beginArray()更改为.beginObject(),但不起作用 此代码是JsonParser public List<Noticias> leerArrayNoticias(JsonReader reader) throws IOException { ArrayList<Noticias> n
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是错误的,因为此JSON包含一个JSON对象,然后是一个JSON数组,其键为
“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
}
[
{"idnoticias":"109","titulo":"nueva1","descripcion":"nuevo1"},
{"idnoticias":"110","titulo":"nueva2","descripcion":"nuevo2"}
]
但是,您的JSON可以优化,因为我们不需要第一个对象。那么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
}
[
{"idnoticias":"109","titulo":"nueva1","descripcion":"nuevo1"},
{"idnoticias":"110","titulo":"nueva2","descripcion":"nuevo2"}
]
如果你有这个JSON,你可以省去上面标记的规则来让它工作。JSON看起来怎么样?问题可能是异常所说的,json以对象而不是数组开始。你说过你试过了,但是你能给我们那个错误的堆栈跟踪吗?试着使用一个对象sais“java.lang.IllegalStateException:预期的BEGIN_对象,但名称是”JSON无效,发布它,这样我就可以更正它的格式,简化标题