Mium
Mium

Reputation: 303

Android: parsing JSONArray key with iterator

I am trying to parse a key from JSONArray which is:

{
    "server": [
       {
         "id": "1",
         "name": "Steve",
         "email": "[email protected]",
         "phone": "1001001000"
       }

    ]
}

Since, the key, which is id, name, email, and phone can be dynamically changed, we have to parse the result without teaching the key value. That is, the system has to parse both the key and the value. So I thought getting an array and using the iterator.hasNext() will solve the problem.

 JSONObject jsonObject = new JSONObject(stringBuilder.toString().trim());
            JSONArray jsonArray = jsonObject.getJSONArray("server");
            for (int current = 0; current < jsonArray.length(); current++){
                JSONObject json_object = jsonArray.getJSONObject(current);
                Iterator iterator = json_object.keys();
                while (iterator.hasNext()){
                    hashMap.put(iterator.next().toString(), json_object.getString(iterator.next().toString()));
                }
            }

It doesn't work properly whether changing the iterator to jsonObject.keys() or json_object.keys(), but only parses the key value of "id", and can't parse the name, email, phone.

This is how I get the JSON file:

$result = mysqli_query($conn, $sql);
$data = array();
if ($result){
     while($row=mysqli_fetch_array($result)){
        array_push($data,
            array('id'=>$row[1],
            'name'=>$row[2],
            'email'=>$row[3],
            'phone'=>$row[4]
        ));
 }
header('Content-Type: application/json; charset=utf8');
$json = json_encode(array("server"=>$data), JSON_PRETTY_PRINT+JSON_UNESCAPED_UNICODE);
echo $json;

Upvotes: 1

Views: 95

Answers (1)

AskNilesh
AskNilesh

Reputation: 69709

Try this

    JSONObject jsonObject = null;
    try {
        jsonObject = new JSONObject(loadJSONFromAsset());
        JSONArray jsonArray = jsonObject.getJSONArray("server");
        for (int current = 0; current < jsonArray.length(); current++){
            JSONObject json_object = jsonArray.getJSONObject(current);
            Iterator iterator = json_object.keys();

            while( iterator.hasNext() ) {

                String key = (String)iterator.next();
                if ( json_object.get(key) instanceof String ) {
                    hashMap.put(key, json_object.getString(key));
                }
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    Log.e("OUTPUT", Arrays.asList(hashMap).toString());

OUTPUT

enter image description here

Upvotes: 1

Related Questions