【问题标题】:Expected BEGIN_ARRAY but was BEGIN_OBJECT parsing JSON预期 BEGIN_ARRAY 但 BEGIN_OBJECT 解析 JSON
【发布时间】:2015-11-10 13:30:17
【问题描述】:

在线上

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"}
    ]
}

【问题讨论】:

  • JSON 长什么样?问题可能是异常所说的,json 以对象而不是数组开头。你说过你试过了,但你能给我们那个错误的堆栈跟踪吗?
  • 尝试使用一个对象 sais "java.lang.IllegalStateException: Expected BEGIN_OBJECT but was NAME"
  • JSON 无效,贴出来让我改正
  • 格式,简化标题

标签: java android arrays reader


【解决方案1】:

你读错了 JSON,因为这个 JSON 包含一个 JSON 对象,然后是一个带有键 "noticias" 的 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 
}

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-24
    • 2019-05-10
    • 1970-01-01
    • 1970-01-01
    • 2014-07-15
    • 2014-08-01
    相关资源
    最近更新 更多