我得到了得到的代码,JSONArrays
但是当我尝试得到JSONObject
只包含一个的代码时,JSONArray
它给了我空白JSONArray
。
例如,如果我需要从中获取数据JSONObject
:
{"events":[{"start":1357714800,"end":1357736400,"name":"Example1","description":""}]}
我得到{"events":[]}
as 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;
}
}
我错过了什么或者这是正常的行为吗?