gpt4 book ai didi

android - 使用 GSON 读取 JSON 数据

转载 作者:行者123 更新时间:2023-11-29 20:54:50 25 4
gpt4 key购买 nike

在过去的 4 个小时里,我查看了各种答案和其他资源,但我根本无法理解 JSON 解析。我需要一些帮助。

这是 JSON 字符串:

{
"success": true,
"categories": [
{
"category_id": "20",
"parent_id": "0",
"name": "Desktops",
"image": "***",
"href": "***",
"categories": null
},
{
"category_id": "25",
"parent_id": "0",
"name": "Components",
"image": "***",
"href": "***",
"categories": null
},
{
"category_id": "34",
"parent_id": "0",
"name": "MP3 Players",
"image": "***",
"href": "***",
"categories": null
}
]
}

这是我的数据类:

public class Data
{
String success;
List<Category> categories;

// Various get/set functions and a toString override

public class Category
{
String category_id;
String name;
String image;

// Various get/set functions
}
}

这是我试图阅读的地方:

private class GetJson extends AsyncTask<String, Void, String>
{
@Override
protected String doInBackground(String... params)
{
String results = "Fail";
URL url = null;
try
{
url = new URL("***");
}

catch (MalformedURLException e)
{
e.printStackTrace();
}

URLConnection ucon = null;

try
{
ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(is));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
{
result += line;
}

Data data = new Gson().fromJson(result, Data.class);

result = data.toString();
}
catch (IOException e)
{
e.printStackTrace();
}

return results;
}

protected void onPostExecute(String result)
{
Toast.makeText(con, result, Toast.LENGTH_SHORT);
}
}

我在堆栈跟踪中根本没有得到任何信息。我检查了亚行几次。一切似乎都正常,但我没有收到 Toast 或错误消息。

我做错了什么?

最佳答案

你忘了展示你的Toast

试试这个

Toast.makeText(con, result, Toast.LENGTH_SHORT).show();

哈哈

进一步

    Data data = new Gson().fromJson(result, Data.class);

result = data.toString();
return result; // need return this

否则总是得到"Fail"

关于android - 使用 GSON 读取 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28067012/

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