簡體   English   中英

org.json.JSONException:無法將 java.lang.String 類型的值 java.io.IOException 轉換為 JSONArray

[英]org.json.JSONException: Value java.io.IOException of type java.lang.String cannot be converted to JSONArray

問題是 json 是從 url 中獲取的(我這么說是因為 url 的整個 json 內容都顯示在“logcat”上),但它以某種方式沒有被轉換為“jsonarray”。

也許語法不正確或什么的,但我已經檢查了所有內容並且看起來沒問題,但仍然拋出了這個異常。

查看代碼並檢查 - JSONArray jArray = new JSONArray(result);

這行可能是問題所在。 “result”是一個字符串doInBackground類型,它在doInBackground函數中被轉換為一個字符串,然后它被發送到onPostExecute函數,在那里它被JSONArray接收,然后執行的其余部分通過。

但據我所知,問題是“結果”到JSONArray的轉換。 這就是拋出的異常所說的。 現在我添加了一行“conn.connect();” 並評論“conn.DoOutput(true)”。 現在我的整個 json 頁面正在被獲取並顯示一個警告,提示“無法轉換 JSONObject 類型的‘整個 json 頁面’的值”

非常感謝幫助的人!!! 這是我的 JSON 文件內容-

     {
  "records": [
    {
      "id": "1",
      "Email": "cde@algowire.com",
      "FirstName": "CDE",
      "LastName": "CDE",
      "Password": "cde",
      "Category": "Chef",
      "Descrption": "cde",
      "Tagline": "Chef LifeStyle",
      "Experience": "2 year 2 months",
      "CurrentWork": "AlgowireTechnologies",
      "Achievements": "got a prize ",
      "Hobbies": "playing,dancing etc"
    },
    {
      "id": "2",
      "Email": "abc@algowire.com",
      "FirstName": "ABC",
      "LastName": "XYZ",
      "Password": "abc",
      "Category": "Engineer",
      "Descrption": "abc",
      "Tagline": "Engineer LifeStyle",
      "Experience": "1 year 3 months",
      "CurrentWork": "AlgowireTechnologies",
      "Achievements": "got a prize ",
      "Hobbies": "playing,dancing etc"
    },
    {
      "id": "3",
      "Email": "demo@algowire.com",
      "FirstName": "DEMO",
      "LastName": "USER",
      "Password": "demo",
      "Category": "Doctor",
      "Descrption": "demo",
      "Tagline": "Doctor LifeStyle",
      "Experience": "2 year 5 months",
      "CurrentWork": "AlgowireTechnologies",
      "Achievements": "got a prize ",
      "Hobbies": "playing,dancing etc"
    },
    {
      "id": "4",
      "Email": "xyz@algowire.com",
      "FirstName": "XYZ",
      "LastName": "XYZ",
      "Password": "xyz",
      "Category": "Engineer",
      "Descrption": "xyz",
      "Tagline": "Engineer LifeStyle",
      "Experience": "2 year 6 months",
      "CurrentWork": "AlgowireTechnologies",
      "Achievements": "got a prize ",
      "Hobbies": "playing,dancing etc"
    },
    {
      "id": "5",
      "Email": "jkl@algowire.com",
      "FirstName": "JKL",
      "LastName": "JKL",
      "Password": "jkl",
      "Category": "Doctor",
      "Descrption": "jkl",
      "Tagline": "Doctor LifeStyle",
      "Experience": "2 year 4 months",
      "CurrentWork": "AlgowireTechnologies",
      "Achievements": "got a prize ",
      "Hobbies": "playing,dancing etc"
    }
  ]
}

代碼

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        //this method will be running on UI thread
        pdLoading.setMessage("\tLoading...");
        pdLoading.setCancelable(false);
        pdLoading.show();

    }

    @Override
    protected String doInBackground(String... params) {
        try {

            // Enter URL address where your json file resides
            // Even you can make call to php file which returns json data
            url = new URL("http://192.168.1.42:81/app_data.json");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return e.toString();
        }
        try {

            // Setup HttpURLConnection class to send and receive data from php and mysql
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestMethod("GET");
            conn.connect();
            // setDoOutput to true as we recieve data from json file
            //conn.setDoOutput(true);

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return e1.toString();
        }

        try {

            int response_code = conn.getResponseCode();

            // Check if successful connection made
            if (response_code == HttpURLConnection.HTTP_OK) {

                // Read data sent from server
                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuffer result = new StringBuffer();
                String line;

                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                // Pass data to onPostExecute method
                return result.toString();

            } else {

                return ("unsuccessful");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return e.toString();
        } finally {
            conn.disconnect();
        }


    }

    @Override
    protected void onPostExecute(String result) {

        //this method will be running on UI thread

        pdLoading.dismiss();
        List<Data> data=new ArrayList<>();

        pdLoading.dismiss();
        try {

            JSONArray jArray = new JSONArray(result);

            // Extract data from json and store into ArrayList as class objects
            for(int i=0;i<jArray.length();i++){
                JSONObject json_data = jArray.getJSONObject(i);
                Data fishData = new Data();
                fishData.did= json_data.getString("id");
                fishData.demail= json_data.getString("Email");
                fishData.dfirst= json_data.getString("Firstname");
                fishData.dlast= json_data.getString("Lastname");
                fishData.dpass= json_data.getString("Password");
                fishData.dcat= json_data.getString("Category");
                fishData.ddesc= json_data.getString("Description");
                fishData.dtag= json_data.getString("Tagline");
                fishData.dex= json_data.getString("Experince");
                fishData.dcurrent= json_data.getString("Currentwork");
                fishData.dachieve= json_data.getString("Achievements");
                fishData.dhobby= json_data.getString("Hobbies");
                data.add(fishData);
            }

            // Setup and Handover data to recyclerview
            mRVFishPrice = (RecyclerView)findViewById(R.id.recycle);
            mAdapter = new AdapterData(MainActivity.this, data);
            mRVFishPrice.setAdapter(mAdapter);
            mRVFishPrice.setLayoutManager(new LinearLayoutManager(MainActivity.this));

        } catch (JSONException e) {
            Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
        }

    }

}

第一個問題是,在 catch 中,您將異常作為函數結果return e.toString()return e.toString() )。

其次,我認為您的 JSON 存在問題。 您可以使用https://jsonformatter.curiousconcept.com/來檢查您的 json 驗證

請將結果轉換為JSONObject

JSONObject jsonObject = new JSONObject(result);

然后嘗試獲取JSONArray

JSONArray arryJ = jsonObject.getJSONArray("記錄");

請檢查 jsonObject 是否為空,因為您也都返回了錯誤消息。 您需要以不同的方式管理錯誤。

還與您分享 json,以便我們可以與您分享確切的問題。

更新答案::

為避免解析錯誤,您可以檢查

if(jsonObject.hasKey("records")){
  //get Value of records
}

正如@Jay 所說,問題實際上出在 JSONArray jarray 上。 該語句必須以 JSONObject 開頭。 喜歡-

            JSONObject a = new JSONObject(s);
            JSONArray jArray = a.getJSONArray("records");

            for(int i=0;i<jArray.length();i++){
                JSONObject json_data = jArray.getJSONObject(i);

當沒有給 JSON 數組指定名稱時,應使用上述代碼。 這意味着在上面的 JSON 中,如果“記錄”不存在,那么問題中的代碼將起作用。 意思是,這行得通——

            //JSONObject a = new JSONObject(s);
            JSONArray jArray = a.getJSONArray(s);

            for(int i=0;i<jArray.length();i++){
                JSONObject json_data = jArray.getJSONObject(i);

感謝所有幫助和嘗試過的人!!!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM