我得到的代碼得到JSONArrays
,但是當我嘗試獲得僅包含一個JSONArray
的JSONObject
時,它會給我空的JSONArray
。嘗試使用一個JSONArray解析JSONObject時的空JSON響應
例如,如果我需要從這個JSONObject
獲取數據:
{"events":[{"start":1357714800,"end":1357736400,"name":"Example1","description":""}]}
我得到{"events":[]}
爲JSONObject
,[]
這意味着它不包含任何JSONArrays。在這種情況下,長度爲JSONObject
也是0.但它不會拋出任何種類的Exceptions
。
但如果JSONObject
包含多個JSONArrays
這樣的:
{"events":[{"start":1357714800,"end":1357736400,"name":"Example1","description":""},{"start":1357714600,"end":1357736500,"name":"Example2","description":""},{"start":1357514800,"end":1357536400,"name":"Example3","description":""}]}
然後我的代碼運行完美。
這裏是我用來解析JSON代碼:
private void getObjects(String url) throws JSONException, Exception {
JSONObject jsonObject = new JSONObject(new NetTask().execute(url).get());
JSONArray job1 = jsonObject.getJSONArray("events");
System.out.println(jsonObject.toString());
System.out.println("JOB1 LENGTH: "+job1.length());
for (int i = 0; i < job1.length(); i++) {
JSONObject jsonEvent = job1.getJSONObject(i);
int start = jsonEvent.getInt("start");
int end = jsonEvent.getInt("end");
String name = jsonEvent.getString("name");
String description = jsonEvent.getString("description");
}
}
public class NetTask extends AsyncTask<String, Integer, String>
{
@Override
protected String doInBackground(String... params)
{
String jsonText = "";
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1) {
buffer.append(chars, 0, read);
}
jsonText = buffer.toString();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return jsonText;
}
}
有什麼不對勁,我很想念,或者這是正常的行爲?
嘗試記錄您從網上收到的Json文本,以確保所有這些東西都在那裏。 – mbwasi