我有一个JSONArray如下。如何按顺序访问其中的每个键和值。
JSONArray = [{"a":1},{"b":2,"c":3},{"d":4},{"e":5,"f":7}]
答案 0 :(得分:8)
您可以尝试以下代码:
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));
}
}
答案 1 :(得分:0)
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));
}
}
}