java.lang.String无法在JsonArray中转换

时间:2017-01-18 12:29:34

标签: java android json

我不知道为什么但是当我尝试从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
  }
]

1 个答案:

答案 0 :(得分:0)

我认为您的问题与您的查询失败(response_code不是200)有关,因此doInBackground会返回"unsuccessful",这显然不是一个数组JSON对象,因此您最终会遇到此异常。您应该返回一个空数组"[]"而不是"unsuccessful"

您的请求可能会失败,因为您的标头Authorization未正确设置,它应以&#34; Basic&#34;然后使用${username}:${password}的{​​{1}}变体进行RFC2045-MIME编码。有关基本身份验证的更多详细信息here