2011-09-20 26 views
2

我有这种格式与动态密钥的JSON用于的Java JSONArray和动态密钥

{ 
    "id":[email protected]", 
    "contact":[ 
    { 
    "uid":0, 
    "name":"johnsmith", 
    "email":[ 
     { 
      "home":"[email protected]" 
     }, 
     { 
      "work":"[email protected]" 
     } 
    ], 
    "mobile":[ 
     { 
      "cc":"+60", 
      "mobile":"00000000" 
     }, 
     { 
      "cc":"+60", 
      "mobile":"00000001" 
     } 
    ] 
    } 
    ] 
} 

我试过电子邮件

Iterator it = contactArray.getJSONObject(i) 
      .getJSONObject("email").keys(); 

但我得到一个错误

org.json.JSONException: JSONObject["email"] is not a JSONObject. 

但这样做的工作,但没有办法从JSONArray获得密钥。

  JSONArray emailArray = contactArray.getJSONObject(i) 
        .getJSONArray("email"); 

如何处理动态密钥?谢谢。

回答

1

数组没有键,它们有元素。这应该是基于Java集合类型,使用循环结构来测试它:

JSONArray emailArray = contactArray.getJSONObject(i).getJSONArray("email"); 

for(Object o: emailArray){ 
    System.out.println(o); 
} 

如果emailArray是空的,什么也不会输出,如果它有它的元素的值将被输出。