java 如何访问 JSONArray 中的每个键和值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29696713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 15:44:44  来源:igfitidea点击:

How can I access each key and value in JSONArray

javajsoniteratorjsonobject

提问by user3712016

I have a JSONArray as below. How can I access each key and value in it in order.

我有一个 JSONArray 如下。如何按顺序访问其中的每个键和值。

JSONArray = [{"a":1},{"b":2,"c":3},{"d":4},{"e":5,"f":7}]

回答by Sach141

You can try following code:

您可以尝试以下代码:

JSONArray jsonArray = new JSONArray("[{\"a\":1},{\"b\":2,\"c\":3},{\"d\":4},{\"e\":5,\"f\":7}]");
for (int i = 0; i < jsonArray.length(); i++) {
    JSONObject json = jsonArray.getJSONObject(i);
    Iterator<String> keys = json.keys();

    while (keys.hasNext()) {
        String key = keys.next();
        System.out.println("Key :" + key + "  Value :" + json.get(key));
    }

}

回答by Karan Sharma

try below code for nested Json .     
 main method here {
     String res = "" ;// your json here 
      ObjectMapper o = new ObjectMapper();
           Object m = o.readValue(res, Object.class);
           printKeys(m);

    }

    public void printKeys(Object obey)
          {

              if ( obey instanceof ArrayList)
              {
                  @SuppressWarnings("unchecked")
                List<Object> list = (List<Object>)obey;
                  for( Object ob : list )
                  {
                     printKeys(ob);
                  }

              }
              else if ( obey instanceof Map)
              {
                 Map<String, Object> m1 = (Map<String,Object>)obey;
                 for ( String key : m1.keySet() ){
                     System.out.println("KEY :"+ key);
                     printKeys(m1.get(key));
              }
          }

          }