我有以下json格式:

[
 { "Otype" : "win"},
 { "Otype" : "win"},
 { },
 { },
 { "Otype" : " win 7"},
 { "Otype" : " Linux"}
]


为了访问Otype,我编写了如下的Java代码:

while(cur.hasNext() && !isStopped()) {
    String json = cur.next().toString();
    JSONObject jObject = new JSONObject(json);
    System.out.print(jObject.getString("Otype"));
}//end of while


因此,以上打印语句仅打印以下结果:

win
win


但不打印:

{ "Otype" : " win 7"}
{ "Otype" : " Linux"}


我认为这可能是值字段中的第一个空格,这就是为什么它不在两个键上方打印的原因,所以我在打印语句中进行了如下更改:

System.out.print(jObject.getString("Otype").trim());


但仍然不起作用:(。

如何使用Java代码访问上述所有json值?

最佳答案

我找到了解决方案。我将代码更改如下:

while(cur.hasNext() && !isStopped()) {
String json = cur.next().toString();
JSONObject jObject = new JSONObject(json);
if(jObject.has("Otype")){
       System.out.print(jObject.getString("Otype"));
   }//end of if
}//end of while

09-05 21:12