JSON 解析器:解析数据时出错 org.json.JSONException: 类型 org.json.JSONArray 无法转换


private class BackTask extends AsyncTask<Void, Void, Void> {
    protected void onPreExecute() {
        super.onPreExecute();
        dialog.show();
    }
    String url = "http://learnd.cf/getOtp.php";
    protected Void doInBackground(Void... params) {
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        list.add(new BasicNameValuePair("username",USERNAME));
        list.add(new BasicNameValuePair("phone",PHONE));
        // getting JSON Object
        // Note that create datas url accepts POST method
        JSONObject json = (JSONObject) jsonParser.makeHttpRequest(url,"GET", list);
        // check log cat fro response
        Log.e("Create Response", json.toString());
        // check for success tag

        return null;
    }
    protected void onPostExecute(Void result) {
        dialog.dismiss();
    }
}

2019-01-12 13:09:36.585 11371-11569/com.example.rajeeshkv.learn_d E/JSON Parser:
    Error parsing data org.json.JSONException: Value 
    [  
        {  
            "temp_id":"12",
            "temp_clg_id":"1",
            "temp_course_id":"1",
            "temp_stud_name":"a",
            "temp_username":"a",
            "temp_password":"a",
            "temp_email":"a",
            "temp_phone":"4",
            "temp_gender":"Male",
            "temp_otp":"2060"
        }
    ]
    of type org.json.JSONArray cannot be converted to JSONObject

这是一个后台任务,用于将用户名和电话传递到数据库并从数据库中获取相应的行,并使用 json 解析器将其传递回 android。但是我收到以下错误。我已经尝试了很多来解决这个问题。有什么办法可以解决这个问题吗?

我认为在获取请求中,您的用户名和电话应该在哈希图中,而不是BasicNameValuePair

> 2019-01-12 13:09:36.585 11371-11569/com.example.rajeeshkv.learn_d E/JSON 解析器:解析数据时出错 org.json.JSONException: 值 [{"temp_id":"12","temp_clg_id":"1","temp_course_id":"1","temp_stud_name":"a","temp_username":"a","temp_password":"a","temp_email":"a","temp_phone":"4","temp_gender":"Male","temp_otp":"2060"}] org.json.JSONArray 无法转换为 JSONObject

这意味着返回值是 JSONArray。但是您正在尝试将其转换为 JSONObject,这是不可能的。

尝试

JSONArray jsonArray = (JSONArray) jsonParser.makeHttpRequest(url,"GET", list);
JSONObject json = jsonArray.get(0);

我曾经jsonArray.get(0)假设 jsonArray 中只有一个对象。如果有更多项目,则必须使用 for 循环进行迭代以获取响应中的所有值。

尝试使用

截击

库并发送请求作为StringRequest

最新更新