我花了4個小時查看各種答案和其他資源,但是我根本無法將我的頭圍繞JSON解析。我需要一些幫助。使用GSON讀取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或錯誤信息。
我在做什麼錯?
所有的成功首先是類型的布爾 – 2015-01-21 12:22:26
使用傑克遜(https://github.com/FasterXML/jackson) – Pierry 2015-01-21 12:22:42
你忘了關閉輸入流.. – smb 2015-01-21 12:28:32