我是android的初学者。我正在创建一个与webservice相关的应用程序。我通过点击url获取json并且我想在listview中显示。我尝试了很多方法但没有结果。我得到了json例外。请帮助我 这是我的json:
[
[
{
"id":"9637",
"country":"Australia",
"time":"14:00",
"type":"country",
"status":"good"
},
{
"id":"9638",
"country":"india",
"time":"16:00",
"type":"country",
"status":"good"
}
]
]
code:
class Response extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
jsonResponse = EntityUtils.toString(httpEntity);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
Toast.makeText(MainActivity.this,jsonResponse,Toast.LENGTH_SHORT).show();
try {
JSONArray jsonArray=new JSONArray(jsonResponse);
for(int i=0;i<jsonArray.length();i++)
{
Toast.makeText(MainActivity.this,""+jsonArray.length(),Toast.LENGTH_SHORT).show();
}
// JSONArray jsonArray=jsonObject.get
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onPostExecute(result);
}
答案 0 :(得分:1)
我认为这段代码是正确的:
try {
JSONArray json=new JSONArray(jsonResponse);
JSONArray jsonArray=json.getJSONArray(0);
for(int i=0;i<jsonArray.length();i++)
{
Toast.makeText(MainActivity.this,""+jsonArray.length(),Toast.LENGTH_SHORT).show();
}
// JSONArray jsonArray=jsonObject.get
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
因为您的JSON响应是一个数组数组。