java - 解析 JSONObject 和 JSONArray 并在 ListView 中修复它们

标签 java android json android-listview arrays

如何解析 JSONObject 中的 JSONArray?这是我从服务器获得的 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的单行中显示每个数组的值,依此类推......

任何帮助将不胜感激。

最佳答案

非常简单..

您需要修复如下代码:

//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

用于获取数组项并将其显示到 ListView 中:

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

}

接下来,将此数组列表作为 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));

关于java - 解析 JSONObject 和 JSONArray 并在 ListView 中修复它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15129638/

相关文章:

java - 无法使用 ZonedDateTime 解析日期

java - 为什么驱动程序在类中找不到方法?

android - 拥有不同版本的源代码,其中一些共同的和一些不同的内容在 git 中

php - 如何使用PHP从JSON提取数据?

java - 测试 Spring MVC 响应模式(忽略响应中项目中的 json 字段)

javascript - JSON 到 HTML 不通过 ID 呈现为 HTML

java - dataTable sortBy 函数不起作用(primefaces)

java - 修改 JSON 结构中的所有字符串基元

java - 如何在android中以编程方式查找网络上其他WiFi设备的IP地址

Android 应用程序在某些设备中显示默认的 android 图标