gpt4 book ai didi

java - 如何将 JSON 信息放入数组中以用于在 ListView 中显示

转载 作者:行者123 更新时间:2023-11-30 03:17:07 25 4
gpt4 key购买 nike

我有一个包含三个 fragment 的 Activity,我正在尝试从我的服务器检索一个 JSON 文件,我将每天更新该文件。

我的 JSON 文件位于: http://pagesbyz.com/test.json

因为有 fragment ,我在我的MainActivity类中使用了如下代码:

DefaultHttpClient   httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://pagesbyz.com/test.json");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");

InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();

inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();

String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
Toast.makeText(getApplicationContext(), result, 2000).show();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}

我真正需要做的是检索我的 JSON 文件中的 TYPE 字段并将其分成三个选项卡并将其放入 ListView 中,如下所示:

enter image description here

我想知道一旦我使用顶部的代码读取了 JSON 文件,我该如何继续...感谢您的帮助:)

我应该查询每个 fragment ,然后查找 TYPE 字段吗?那会更容易吗?

想知道为什么 Toast 没有执行...这是我主要 Activity 的 pastebin:http://pastebin.com/gKTCeH79

最佳答案

您要做的是使用 Android 的 JSONObject 和 JSONArray 来访问您的 json 数据。

例如,由于您的根是一个 json 数组,您希望从您拥有的 json 数据实例化一个 JSONArray 对象。

JSONArray jsonArray = new JSONArray(jsonString);

现在,您可以从此数组中为数组中的每个对象获取单独的 JSONObject。

JSONObject objectOne = new JSONObject(0); // Grabs your first item

您现在可以从 JSONObject 访问您的三个值。

String type = objectOne.get("type") // Will give you the value for type

JSON 数组:http://developer.android.com/reference/org/json/JSONArray.html

JSON对象:http://developer.android.com/reference/org/json/JSONObject.html

另一种方法是使用一个框架,让您可以将 json 反序列化为 Java POJO(普通旧 Java 对象)。 Gson 是最容易使用的。

基本思想是创建一个与 json 对象直接相关的对象,有了这个对象后,您可以轻松地将数据存储在 java 对象中,并随心所欲地使用它。

GSON 示例:

Gson gson = new Gson();
MyCustomClass obj2 = gson.fromJson(json, MyCustomClass.class);

MyCustomClass 将包含变量 id、type 和 data。

GSON 引用:https://sites.google.com/site/gson/gson-user-guide

祝你好运!

关于java - 如何将 JSON 信息放入数组中以用于在 ListView 中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19868439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com