有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在不知道名称的情况下获取JSONObject中的第一个对象?

我有一个JSONObject包含其他对象:

{
"1" : {
        "state": [],
        "hue": 224
      }
"2" : {
        "state": [],
        "hue": 224
      }
"3" : {
        "state": [],
        "hue": 224
      }
}

这是飞利浦Hue Brigde JSON的响应,包含所有连接的灯。我使用截击进行http连接。 我创建了一个Light类,在其中存储状态、色调、bri等数据。我在Volley的onResponse中使用for循环填充Light类:

for (int i = 0; i <= response.length(); i++) {
     JSONObject lightObject = response.getJSONObject(String.valueOf(i)); 
     System.out.println("OBJECT " + lightObject);

     // Use try/catch because of empty or unknown key
                try {
                    description = lightObject.getString("type");
                } catch (Exception e) {}
                try {
                    bri = lightObjectState.getInt("bri");
                } catch (Exception e) {}

                try {
                    sat = lightObjectState.getInt("sat");
                } catch (Exception e) {}

                try {
                    hue = lightObjectState.getInt("hue");
                } catch (Exception e) {}

     Light light = new Light(String.valueOf(i),lightObject.getString("name"), description, on, bri, sat, hue);
     mLightList.add(light);
     mLightAdapter.notifyDataSetChanged();

}

for循环的问题是,当Light id开始大于零时,它将使我的Android应用程序崩溃,因为存在no value of 0。 我的问题是如何在不知道包含对象的key名称的情况下获取响应的第一个对象,该名称具有一个灯光的所有属性,因此当JSONObject看起来如下时,应用程序将不会崩溃,而只显示灯光4到6:

{
"4" : {
        "state": [],
        "hue": 224
      }
"5" : {
        "state": [],
        "hue": 224
      }
"6" : {
        "state": [],
        "hue": 224
      }
}

如果还有什么问题,请告诉我。 谢谢


共 (3) 个答案

  1. # 1 楼答案

        // use keys() iterator, you don't need to know what keys are there/missing
        Iterator<String> iter = response.keys();
        while (iter.hasNext()) {
            String key = iter.next();
            JSONObject lightObject = response.getJSONObject(key); 
            System.out.println("key: " + key + ", OBJECT " + lightObject);
    
            // you can check if the object has a key before you access it
            if (lightObject.has("bri")) {
                bri = lightObject.getInt("bri");
            }
    
            if (lightObject.has("sat")) {
                sat = lightObject.getInt("sat");
            }
    
            if (lightObject.has("hue")) {
                hue = lightObject.getInt("hue");
            }
    
            if (lightObject.has("name")) {
                name = lightObject.getString("name")
            }
    
            Light light = new Light(key, name, description, on, bri, sat, hue);
            mLightList.add(light);
        }
    
        mLightAdapter.notifyDataSetChanged();
    
  2. # 2 楼答案

    假设你有一个叫做灯泡的类

    public class Bulb {
    
        int[] state;
        int hue;
    
    }
    

    然后可以使用类似GSON的JSON序列化程序

    然后,您可以将您的响应映射到以下映射(如HashMap)中

    Type typeOfHashMap = new TypeToken<Map<String, Bulb>>() { }.getType();
    
    Map<String,Bulb> bulbMap = gson.fromJson(json, typeOfHashMap); 
    

    然后你可以用这样的键在地图上迭代

    Iterator bulbIterator = bulbMap.entrySet().iterator();
    
      while (bulbIterator.hasNext()) {
    
        Map.Entry pair = (Map.Entry)bulbIterator.next();
    
        String pKey = (String) pair.getKey();
    
        Bulb bulb = (Bulb) pair.getValue();
    
        // Do something here with the bulb
    }
    
  3. # 3 楼答案

    尝试使用对象键:

     Iterator<String> keys = jsonObject.keys();
     if( keys.hasNext() ){
         String key = (String)keys.next(); // First key in your json object
      }