簡體   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