首页 > 解决方案 > Android 中 JSONObject 与 JSONArray 的问题

问题描述

我猜我有一个非常具体的问题。我正在使用 Volley 库从 URL 获取字符串响应,响应如下:

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

我通过在 PHP 中将我的 SQL 查询数组转换为 JSON 来得到这个响应

    $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";

接下来我需要做的是通过这个 JSON 并将记录插入到我的 Android APP 中的本地数据库中。为此,我执行以下操作:

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());
              }
          }

我不断收到以下错误:

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

知道我可以在 PHP 端做什么来更改 JSONString(添加 [],或向数组添加名称),或者我需要在 Android 中做什么?

标签: javaphpandroidandroid-volley

解决方案


我建议您在调用应用程序时使用 aJsonObjectRequest而不是。它与 StringRequest 几乎相同,但它得到了一个答案。StringRequestVolleyJSONObject

String url = "http://my-json-feed";

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
    (Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

@Override
public void onResponse(JSONObject response) {
    // your cose goes here:
       
       JSONObject jsonObject = new JSONObject(response.toString());

       User user = new User();
       user.email= jsonObject.getString("email");
       user.phone=jsonObject.getString("phone");
       user.firstName=jsonObject.getString("name");
       user.lastName=jsonObject.getString("family_name");
       user.role=jsonObject.getInt("role");
       user.token="123123123fsadf";

      insertUser inewuser = new insertUser();
      inewuser.execute(user);


}
}, new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError error) {
    // TODO: Handle error

}
});

jsonObjectRequest


推荐阅读