【问题标题】:Problems with JSONObject vs JSONArray in AndroidAndroid 中 JSONObject 与 JSONArray 的问题
【发布时间】:2021-09-28 14:27:18
【问题描述】:

我猜我有一个非常具体的问题。我正在使用 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 中做什么?

【问题讨论】:

标签: java php android android-volley


【解决方案1】:

您的响应没有 json 数组,只有一个对象。 数组是这样的。

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

所以删除循环并尝试。

if(response.contains("email")) {
  testResponse.setText("Response is2: " + response);
    try {
         
        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());
           }
}

【讨论】:

    【解决方案2】:

    我建议您在应用中调用Volley 时使用JsonObjectRequest 而不是StringRequest。它与 StringRequest 几乎相同,但它得到一个 JSONObject 作为答案。

    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

    【讨论】:

    • 我执行字符串请求以执行基于字符串的 IF
    • 你可以从我为你写的 Json obj 中获取字符串……你现在明白了吗?
    • 是的,谢谢,我混淆了对象和数组,因为在示例中到处都使用数组,谢谢
    【解决方案3】:

    您的 json 字符串有一个 json 对象作为根对象,而在代码中您使用 JSONArray jsonArr = new JSONArray(response); 将其解析为一个数组。假设您使用了 json 库,您必须开始使用以下方法解析 json:

    JSONObject jsonObj = new JSONObject(response);
    

    替代方法是实际生成一个 json 数组 ([...]) 而不是 json 对象 ({...}),以便您的解析代码能够识别它。您要做出的选择取决于您是始终发送单个 json 对象还是希望能够发送多个 json 对象(在 json 数组中)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-15
      • 1970-01-01
      • 1970-01-01
      • 2015-09-13
      相关资源
      最近更新 更多