我花了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或错误消息。
我做错了什么?
答案 0 :(得分:2)
您忘了展示自己的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"
答案 1 :(得分:0)
//First generate getter setter of data class variables.
TypeToken<Data> tokenPoint1 = new TypeToken<Data>() {};
//SYSO result string here for Confirmation
Gson gson = new Gson();
Data dataobj= gson.fromJson(result, tokenPoint1.getType());
// syso dataobj.getname();
//希望这对你有用