繁体   English   中英

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

[英]JSON Parser: Error parsing data org.json.JSONException: type org.json.JSONArray cannot be converted

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列表

正如花括号( [] )所建议的那样,您提供的json是一个数组json,而不是json对象。

试试这个

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

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”: “一”, “temp_username”: “一”, “temp_password”: “一”, “temp_email”: “一”, “temp_phone”:“4不能将类型为org.json.JSONArray的“,” temp_gender“:”男“,” temp_otp“:” 2060“}]转换为JSONObject

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

尝试

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

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

尝试使用

齐射

库并将请求作为StringRequest发送。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM