ser*_*sly 22 arrays json json-rpc
我正在开发一个Android应用程序,它获取名为"WebUntis"的Web服务的json内容.我得到的Json内容看起来像:
{"jsonrpc":"2.0","id":"req-002",
"result":[
{"id":125043,"date":20110117,"startTime":800,"endTime":850,
"kl":[{"id":71}],
"te":[{"id":23}],
"su":[{"id":13}],
"ro":[{"id":1}]},
{"id":125127,"date":20110117,"startTime":1055,"endTime":1145,
"kl":[{"id":71}],
"te":[{"id":41}],
"su":[{"id":19}],
"ro":[{"id":31}]},
...]}
Run Code Online (Sandbox Code Playgroud)
正如您在结果数组中看到的那样,还有其他数组,如"kl","su"和"ro"
我正在获取这些数组的内容,然后我将它们存储在一个arraylist中.但是,当其中一个数组为空时,就像;
{"jsonrpc":"2.0","id":"req-002",
"result":[
{"id":125043,"date":20110117,"startTime":800,"endTime":850,
"**kl":[]**,
"te":[{"id":23}],
"su":[{"id":13}],
"ro":[{"id":1}]},
{"id":125127,"date":20110117,"startTime":1055,"endTime":1145,
"kl":[{"id":71}],
"te":[{"id":41}],
"su":[{"id":19}],
"ro":[{"id":31}]},
...]}
Run Code Online (Sandbox Code Playgroud)
我总是得到错误IndexOutOfRangeException,但我总是告诉它它不应该采用空数组,这是我尝试过的:
JSONObject jsonResult = new JSONObject(s);
// Get the result object
JSONArray arr = jsonResult.getJSONArray("result");
for (int i = 0; i < arr.length(); i++) {
JSONObject c = arr.getJSONObject(i);
anfangStunde[i] = c.getString("startTime");
endeStunde[i] = c.getString("endTime");
// get the jsonarrays (kl, su, ro)
kl = c.getJSONArray("kl");
su = c.getJSONArray("su");
ro = c.getJSONArray("ro");
// check if kl is not null
if(kl != null){
klassenID[i] = kl.getJSONObject(0).getString("id");
}
if (klassenID[i] != null) {
klasse = webuntis.klassenMap.get(klassenID[i]);
Log.d("ID und Klasse=", "" + klassenID[i] + ";" + klasse);
}
// get th ids
fachID[i] = su.getJSONObject(0).getString("id");
if (fachID[i] != null) {
fach = webuntis.faecherMap.get(fachID[i]);
Log.d("ID und Fach=", "" + fachID[i] + ";" + fach);
}
// "Start;Ende;Klasse;Fach;Raum" store in arraylist
webuntis.stundenPlan.add(anfangStunde[i] + ";" + endeStunde[i] + ";" + klasse + ";" + fach);
// Write Data into a file for offline use:
}
Run Code Online (Sandbox Code Playgroud)
谁能帮我 ?
T.G*_*lle 41
如果数组在文件中定义但是为空,如:
...
"kl":[]
...
Run Code Online (Sandbox Code Playgroud)
然后getJSONArray("kl")将返回一个空数组,但该对象不是null.然后,如果你这样做:
kl = c.getJSONArray("kl");
if(kl != null){
klassenID[i] = kl.getJSONObject(0).getString("id");
}
Run Code Online (Sandbox Code Playgroud)
kl是不 null与kl.getJSONObject(0)将抛出异常-有数组中没有第一个元素.
相反,你可以检查length(),例如:
kl = c.getJSONArray("kl");
if(kl != null && kl.length() > 0 ){
klassenID[i] = kl.getJSONObject(0).getString("id");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
53733 次 |
| 最近记录: |