目前,我正试图在Android的ListView
中显示JSON数据(托管在网络服务器上)。应用程序正确接收数据但无法进一步处理以在ListView
中显示它。
错误如下:
JSON parsing error: Value ... of type org.json.JSONArray cannot be converted to JSONObject
我尝试解析的JSON数据如下所示:
[{"idBuch":1,"autor":"Erich Maria Remarque","name":"Im Westen nichts Neues","preis":20,"buchtyp":{"idBuchtyp":3,"typenamen":"Geschichte"}}]
处理收到的JSON-String的代码:
try{
JSONObject jsonObject = new JSONObject(jsonStr);
JSONArray books = jsonObject.getJSONArray("book");
for(int i = 0; i < books.length(); i++){
JSONObject obj = books.getJSONObject(i);
String idBook = obj.getString("idBuch");
String author = obj.getString("autor");
String name = obj.getString("name");
String price = obj.getString("preis");
JSONObject booktype = obj.getJSONObject("buchtyp");
String idBooktype = booktype.getString("idBuchtyp");
String typename = booktype.getString("typenamen");
HashMap<String, String> book = new HashMap<>();
book.put("idBook", idBook);
book.put("author", author);
book.put("name", name);
book.put("price", price);
book.put("genre", typename);
bookList.add(book);
} }catch(final JSONException e)
我知道这个网站上有很多类似的问题,但我在这个问题上仍然没有成功。提前谢谢。
答案 0 :(得分:2)
您提供的JSON只包含一个数组。
[
{
"idBuch": 1,
"autor": "Erich Maria Remarque",
"name": "Im Westen nichts Neues",
"preis": 20,
"buchtyp": {
"idBuchtyp": 3,
"typenamen": "Geschichte"
}
}
]
但是,您的代码希望root是一个带有字段簿的对象。
{
"book": [
{
"idBuch": 1,
"autor": "Erich Maria Remarque",
"name": "Im Westen nichts Neues",
"preis": 20,
"buchtyp": {
"idBuchtyp": 3,
"typenamen": "Geschichte"
}
}
]
}
在这种情况下,请尝试替换该行:
JSONObject jsonObject = new JSONObject(jsonStr);
带
JSONArray books = new JSONArray(jsonStr);
正常进行。您的最终结果应如下所示:
try {
JSONArray books = new JSONArray(jsonStr);
for (int i = 0; i < books.length(); i++) {
JSONObject obj = books.getJSONObject(i);
String idBook = obj.getString("idBuch");
String author = obj.getString("autor");
String name = obj.getString("name");
String price = obj.getString("preis");
JSONObject booktype = obj.getJSONObject("buchtyp");
String idBooktype = booktype.getString("idBuchtyp");
String typename = booktype.getString("typenamen");
HashMap < String, String > book = new HashMap < > ();
book.put("idBook", idBook);
book.put("author", author);
book.put("name", name);
book.put("price", price);
book.put("genre", typename);
bookList.add(book);
}
} catch (final JSONException e) {
e.printStackTrace()
}