0

如何解析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&apos;s lap. <b>laptop</b> [ˈlæpˌtɒp], <b>laptop</b> computer. n (Electronics &amp; Computer Science / Computer ..."
    ],
    "links": [
        "http://en.wikipedia.org/wiki/Laptop",
        "http://www.thefreedictionary.com/laptop"
    ],
    "nextpage": ""
}
}

我可以得到JSONObject但是如何一个一个地得到 JSONArray,这样我就可以在listview.

我想在单行中显示每个数组的值,listview依此类推....

任何帮助将不胜感激。

4

3 回答 3

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);

}

接下来,您将这个数组列表作为列表视图的源,如下所示:

 // 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));
于 2013-02-28T07:23:21.943 回答
1

考虑到您的顶级 JSON 将被解析为,并且随后您可以通过方法和JSONObject请求从它接收任何子级别对象和/或数组。您感兴趣的数组在 JSON 层次结构中有两个层次,因此您需要这样的东西:getJSONObject(name)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用作示例):

for(int i = 0; i < titlesObj.length(); i++) {
    String title = titlesObj.getString(i);
}
于 2013-02-28T07:23:51.387 回答
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");
于 2013-02-28T07:23:15.877 回答