我的JSON数组如下: [{ “ID”: “1”, “名称”: “ABC”},{ “ID”: “2”, “名称”: “XYZ”}]
我希望它被解析。
我这样做了:
protected JSONObject doInBackground(String... args)
{
json = jParser.getJSONFromUrl(url);
//Log.e("JSON Data", json.toString());
return json;
}
protected void onPostExecute(JSONObject json)
{
pDialog.dismiss();
// Getting JSON Array from URL
mydataset = json.getJSONArray("data");
Log.d("Till Here", mydataset.toString());
}
但是“Till Here”并没有出现在日志中,这意味着我正在做其他事情。 有人可以帮忙吗?
答案 0 :(得分:0)
我建议您使用optJSONArray()
类似
mydataset = json.optJSONArray("data");
因为它不需要被try / catch包围,但你应该小心null
另外,我们看不到JSONObject json
是什么 - 它是JSONObject
还是JSONArray
?如果它是第二个,那么您的代码是错误的,因为您需要操作JSONArray
而不是JSONObject
:
protected JSONArray doInBackground(String... args)
{
json = jParser.getJSONFromUrl(url);
Log.d("JSON Data", json.toString());
return json;
}
protected void onPostExecute(JSONArray json)
{
pDialog.dismiss();
// Got JSON Array from URL already
Log.d("b4 tHere", String.valueOf(json));
mydataset = json;
Log.d("Till Here", String.valueOf(mydataset));
}
答案 1 :(得分:0)
public static JSONArray getJSONfromURL(String url){
InputStream is = null;
String result = "";
JSONArray jArray = null;
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
jArray = new JSONArray(result);
return jArray;
}
}
protected JSONArray doInBackground(String... args)
{
json = jParser.getJSONFromUrl(url);
//Log.e("JSON Data", json.toString());
return json;
}
protected void onPostExecute(JSONArray json)
{
pDialog.dismiss();
try {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsobj = jsonArray.getJSONObject(i);
String id = jsobj.getString("id");
String name = jsobj.getString("name");
Log.e("MainActivity"," >>> id = " + id + " >> name = " +name);
}
} catch (JSONException e) {
}
}