簡體   English   中英

java.lang.String無法在JsonArray中轉換

[英]java.lang.String cannot be converted in JsonArray

我不知道為什么但是當我嘗試從JSON獲取數據時出現此錯誤:

java.lang.String無法在Jsonarray中轉換

這是我的代碼,

主要活動:

public class MainActivity extends AppCompatActivity {

    // CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
    public static final int CONNECTION_TIMEOUT = 10000;
    public static final int READ_TIMEOUT = 15000;
    private RecyclerView mRVFishPrice;
    private AdapterProgram mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Make call to AsyncTask
        new AsyncFetch().execute();
    }

    private class AsyncFetch extends AsyncTask<String, String, String> {
        ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
        HttpURLConnection conn;
        URL url = null;

        @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://v1.tvguideapi.com/programs?channels[]=2161&channels[]=2162&channels[]=2163&start=1484685000&stop=1484690400");

            } 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.addRequestProperty("Authorization", "nSLkk3o6xowTgXryFVxWaVSRW3zxNwlzmYIcgCkE");
                conn.setRequestMethod("GET");

                // 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));
                    StringBuilder result = new StringBuilder();
                    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<Programs> 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);
                    Programs fishData = new Programs();
                    fishData.title= json_data.getString("title");
                    fishData.description= json_data.getString("description");
                   // fishData.catName= json_data.getString("cat_name");
                   // fishData.sizeName= json_data.getString("size_name");
                   // fishData.price= json_data.getInt("price");
                    data.add(fishData);
                }

                // Setup and Handover data to recyclerview
                mRVFishPrice = (RecyclerView)findViewById(R.id.fishPriceList);
                mAdapter = new AdapterProgram(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();
            }

        }

    }
}

JSON:

[
  {
    "id": "18631557",
    "start": "2017-01-17 21:03:00",
    "stop": "2017-01-17 22:55:00",
    "lang": "",
    "title": "The Town",
    "subtitle": "",
    "description": "Regia: Ben Affleck - Cast: Jeremy Renner, Blake Lively, Ben Affleck, Jon Hamm. POLIZIESCO 120' - Stati Uniti D'America, 2010.",
    "category": "",
    "channel_id": "2142",
    "icon": null,
    "ts_start": 1484686980,
    "ts_stop": 1484693700
  }
]

我相信你的問題與你的查詢失敗的事實有關( response_code不是200 )所以doInBackground返回"unsuccessful" ,這顯然不是JSON對象的數組,所以你最終得到這個例外。 您應該返回一個空數組"[]"而不是"unsuccessful"

您的請求可能會失敗,因為您的標頭Authorization未正確設置它應該以“ Basic ”開頭,后跟${username}:${password}使用Base64RFC2045-MIME變體編碼。 有關基本身份驗證的更多細節在這里

暫無
暫無

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

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