Problems with JSONObject vs JSONArray in Android

I have a pretty specific problem I guess. I'm using Volley library to get a String response from URL, the response is following:

{"email":"imribar@gmail.com","phone":"7(707)990-77-71","family_name":"Жилин","name":"Иван","role":0}

I get this response by converting my SQL query array to JSON in PHP

    $output=$db->query("SELECT email, phone, family_name, name, role FROM users WHERE email=?", "$email")->fetchArray();

    $json=json_encode($output, JSON_UNESCAPED_UNICODE);
    echo"$json";

What I need to do next is go throught this JSON and insert records to local database in my Android APP. In order to do that, I do following:

if(response.contains("email")) {
  testResponse.setText("Response is2: " + response);
    try {
         JSONArray jsonArr = new JSONArray(response);
        for(int i=0; i < jsonArr.length();i++){
            JSONObject jsonObj = jsonArr.getJSONObject(i);
            Log.i("User",jsonObj.toString());
    
           User user = new User();
           user.email= jsonObj.getString("email");
           user.phone=jsonObj.getString("phone");
           user.firstName=jsonObj.getString("name");
           user.lastName=jsonObj.getString("family_name");
           user.role=jsonObj.getInt("role");
           user.token="123123123fsadf";
    
          insertUser inewuser = new insertUser();
          inewuser.execute(user);
           }
            } catch (JSONException e) {
              Log.i("JSONerror", e.toString());
              }
          }

I keep getting the following error:

 13:24:59.518 22389-22389/com.pasha.ikeenschool I/JSONerror: org.json.JSONException: Value {"email":"imribar@gmail.com","phone":"7(707)990-77-71","family_name":"Жилин","name":"Иван","role":0} of type org.json.JSONObject cannot be converted to JSONArray

Any idea what I can do on PHP side to change the JSONString (add [], or add a name to an array), or what do I need to do in Android?



Read more here: https://stackoverflow.com/questions/68465653/problems-with-jsonobject-vs-jsonarray-in-android

Content Attribution

This content was originally published by Undry at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: