尽管JSONObject具有值,但它返回null

时间:2015-11-09 17:29:59

标签: java android json jsonobject

这4行简单的代码:

JSONObject curr = jsonArray.getJSONObject(i);
System.out.println("the line" + curr.getString("post"));
System.out.println("id: " + curr.optString("id"));
System.out.println("name: " + curr.optString("name"));

打印以下输出:

11-09 17:15:05.890 1580-1626/yuvallevy.powertoolsrental I/System.out: the line{"id":"0","name":"פטישי חציבה"}
11-09 17:15:05.890 1580-1626/yuvallevy.powertoolsrental I/System.out: id: 
11-09 17:15:05.890 1580-1626/yuvallevy.powertoolsrental I/System.out: name: 
11-09 17:15:05.890 1580-1626/yuvallevy.powertoolsrental I/System.out: the line{"id":"1","name":"מקדחות יהלום"}
11-09 17:15:05.890 1580-1626/yuvallevy.powertoolsrental I/System.out: id: 
11-09 17:15:05.890 1580-1626/yuvallevy.powertoolsrental I/System.out: name: 
11-09 17:15:05.890 1580-1626/yuvallevy.powertoolsrental I/System.out: the line{"id":"2","name":"מהדקי אדמה"}
11-09 17:15:05.890 1580-1626/yuvallevy.powertoolsrental I/System.out: id: 
11-09 17:15:05.890 1580-1626/yuvallevy.powertoolsrental I/System.out: name: 
11-09 17:15:05.890 1580-1626/yuvallevy.powertoolsrental I/System.out: the line{"id":"3","name":"מכונות פוליש"}
11-09 17:15:05.890 1580-1626/yuvallevy.powertoolsrental I/System.out: id: 
11-09 17:15:05.890 1580-1626/yuvallevy.powertoolsrental I/System.out: name: 

有人可以帮助我理解,如果我打印整条线明确表示每行都有“id”并且还有“name”,当我尝试只得到它们的值时,我会得到空的结果吗? / p>

这是JSONArray:

[{"post":{"id":"0","name":"פטישי חציבה"}},{"post":{"id":"1","name":"מקדחות יהלום"}},{"post":{"id":"2","name":"מהדקי אדמה"}},{"post":{"id":"3","name":"מכונות פוליש"}}]

那是一个帖子:

{"id":"0","name":"פטישי חציבה"}

1 个答案:

答案 0 :(得分:0)

您可能想要这样做:

JSONObject curr = jsonArray.getJSONObject(i);
System.out.println("id: " + curr.optJSONObject("post").optString("id"));
System.out.println("name: " + curr.optJSONObject("post").optString("name"));