[英]Android - How to extract nested value from JSON string
This is my String gathered from a JSON file. 这是我从JSON文件中收集的String。 It is as expected: 符合预期:
{
"catalog":{
"book":{
"id":"bk101",
"author":"Gambardella, Matthew",
"title":"XML Developer's Guide",
"genre":"Computer",
"price":"44.95",
"publish_date":"2000-10-01",
"description":"An in-depth look at creating applications with XML."
}
}
}
Using this String I created a JSONObject.. 使用此字符串,我创建了一个JSONObject。
JSONObject jsonBook = new JSONObject(sb.toString());
Then I am simply trying to extract some of the parameters seen in the string such as id and author. 然后,我只是尝试提取一些在字符串中看到的参数,例如id和author。
"id": "bk101"` `"author": "Gambardella, Matthew"
This is my approach.. 这是我的方法
book.setAuthor(jsonBook.getString(Book.AUTHOR));
book.setId(jsonBook.getString(Book.ID));
Yet I keep getting errors saying there is no value for id/author whichever one is first. 但是我不断收到错误消息,说id / author没有价值,以先到者为准。 Any ideas? 有任何想法吗?
Cheers 干杯
That's because id
and author
are both inside book, not inside the json root 那是因为id
和author
都在书里面,而不是json根里面
JSONObject jsonBook = new JSONObject(sb.toString());
JSONObject catalogue = jsonBook.getJSONObject("catalog");
JSONObject jbook = catalogue.getJSONObject("book");
book.setAuthor(jbook.getString(Book.AUTHOR));
book.setId(jbook.getString(Book.ID));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.