如何在JSONArray
内解析JSONObject
?以下是我从服务器获取的JSON
响应。
{
"searchdata": {
"titles": [
"<b>Laptop</b> - Wikipedia, the free encyclopedia",
"<b>laptop</b> - definition of <b>laptop</b> by the Free Online Dictionary ..."
],
"desc": [
"A <b>laptop</b> computer is a personal computer for mobile use. A <b>laptop</b> has most of the same components as a desktop computer, including a display, a keyboard, a ...",
"lap·top (l p t p) n. A portable computer small enough to use on one's lap. <b>laptop</b> [ˈlæpˌtɒp], <b>laptop</b> computer. n (Electronics & Computer Science / Computer ..."
],
"links": [
"http://en.wikipedia.org/wiki/Laptop",
"http://www.thefreedictionary.com/laptop"
],
"nextpage": ""
}
}
我能够获得JSONObject
但是如何逐个获取JSONArray,以便我可以在listview
中修复它们。
我想在listview
的一行中显示每个数组的值,依此类推......
任何帮助将不胜感激。
答案 0 :(得分:1)
非常容易..
你需要修改这样的代码:
//jsonString is your whole JSONString which you have shown above
JSONObject jObj = new JSONObject(jsonString);
JSONObject jSearchData = jObj.getJSONObject("searchdata");
JSONArray jTitles = jSearchData.getJSONArray("titles");
JSONArray jDesc= jSearchData.getJSONArray("desc");
JSONArray jLinks= jSearchData.getJSONArray("links");
String nextPage = jSearchData.getString("nextpage");
//and so on and so forth
用于获取数组项并将其显示在列表视图中:
//you can iterate over each item and add it to an ArrayList like this:
//i am showing you a single one,follow the same process for other arrays:
ArrayList titlesArray = new ArrayList();
for (int i = 0; i < jTitles.length(); i++) {
String item = jTitles.getString(i);
titlesArray.add(item);
}
接下来,你让这个arraylist成为这样的listview的源:
// Get a handle to the list view
ListView lv = (ListView) findViewById(R.id.ListView01);
lv.setAdapter(new ArrayAdapter<string>((Your activity class).this,
android.R.layout.simple_list_item_1, titlesArray));
答案 1 :(得分:1)
考虑将您的顶级JSON解析为JSONObject
,随后您可以通过方法getJSONObject(name)
和{{请求从中接收任何子级别对象和/或数组1}}。您感兴趣的数组在JSON层次结构中有两个级别,所以您需要这样的内容:
getJSONArray(name)
您可以这样迭代任何数组(以String json = ...;
JSONObject rootObj = new JSONObject(json);
JSONObject searchObj = rootObj.getJSONObject("searchdata");
JSONArray titlesObj = searchObj.getJSONArray("titles");
JSONArray descsObj = searchObj.getJSONArray("desc");
JSONArray linksObj = searchObj.getJSONArray("links");
为例):
titles
答案 2 :(得分:0)
这将有所帮助:
JSONArray titles = new jSONObject(jsonstring).getJSONObject("searchdata").getJSONArray("titles");
JSONArray desc = new jSONObject(jsonstring).getJSONObject("searchdata").getJSONArray("desc");
JSONArray links = new jSONObject(jsonstring).getJSONObject("searchdata").getJSONArray("links");