开发者

Java JSONArray and Dynamic keys

开发者 https://www.devze.com 2023-04-06 04:59 出处:网络
I have a JSON of this format with dynamic keys for the email { \"id\":johnsmith@gmail.com\", \"contact\":[

I have a JSON of this format with dynamic keys for the email

{
   "id":johnsmith@gmail.com",
   "contact":[
  {
     "uid":0,
     "name":"johnsmith",
     "email":[
        {
           "home":"johnsmith0@gmail.com"
        },
        {
           "work":"johnsmith1@gmail.com"
        }
     ],
     "mobile":[
        {
           "cc":"+60",
           "mobile":"00000000"
        },
        {
           "cc":"+60",
           "mobile":"00000001"
        }
     ]
  }
   ]
}

I tried

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

But i'm getting an error

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

But doing this works, but there is no method to get keys from a JSONArray.

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

Ho开发者_高级运维w to handle dynamic keys? Thanks.


Arrays don't have keys, they have elements. This should be based on a java collection type, use a loop structure to test it:

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

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

If the emailArray is empty, nothing will be output, if it has elements in it the value will be output.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号