解码json在Java中返回null

时间:2014-08-27 15:42:47

标签: java json

我有以下JSONArray

[
   {
      "Lng":17.908817,
      "name":"S1",
      "id":1,
      "sensor:":[
         "Temperature",
         "Wind"
      ],
      "Lat":47.089492
   },
   {
      "Lng":17.908458,
      "name":"S2",
      "id":2,
      "sensor:":[
         "Temperature",
         "Wind",
         "Humidity"
      ],
      "Lat":47.089246
   },
   {
      "Lng":17.908222,
      "name":"S3",
      "id":3,
      "sensor:":[
         "Wind"
      ],
      "Lat":47.089662
   }
]

我可以将其拆分为JSONObject,但如果我尝试拆分Object,则会返回null

我的代码:

    Object object = JSONValue.parse(result);
    JSONArray array = (JSONArray)object;
    for(int i = 0 ; i < array.size(); i++){
        System.out.println(array.get(i));

        JSONObject jsonObject = (JSONObject)array.get(i);

        for(int j = 0 ; j < jsonObject.size(); j++){
            System.out.println(jsonObject.get(j));

        }

    }

结果:

{"Lng":17.908817,"name":"S1","sensor:":["Temperature","Wind"],"id":1,"Lat":47.089492}
null
null
null
null
null
{"Lng":17.908458,"name":"S2","sensor:":["Temperature","Wind","Humidity"],"id":2,"Lat":47.089246}
null
null
null
null
null
{"Lng":17.908222,"name":"S3","sensor:":["Wind"],"id":3,"Lat":47.089662}
null
null
null
null
null

3 个答案:

答案 0 :(得分:3)

JSONObject(JSON对象)不可索引。元素是无序的。你想做什么

System.out.println(jsonObject.get(j));

没有意义。通过名称访问名称 - 值对。

答案 1 :(得分:0)

您可以使用:

Iterator<?> keys = jsonObject.keys();

while( keys.hasNext() ){
    String key = (String)keys.next();
    // use jsonObject.get(key)
}

而不是“j”。

答案 2 :(得分:0)

尝试通过密钥访问JSONObject属性:

JSONArray array = JSONValue.parse(result);
for(int i = 0 ; i < array.size(); i++) 
{
  System.out.println(array.get(i));
  JSONObject jsonObject = (JSONObject) array.get(i);
  int id = jsonObject.getInt("id");
  String lng = jsonObject.getString("Lng");
  String lat = jsonObject.getString("Lat");
  Object sensor = jsonObject.getString("sensor");
  String name = jsonObject.getString("name");
  System.out.println(id);
  System.out.println(name);
  System.out.println(sensor);
  System.out.println(lat);
  System.out.println(lon);
}