无法解析json - String无法转换为JSONArray

时间:2017-04-25 00:16:44

标签: java android json parsing

尝试从https://jsonplaceholder.typicode.com/users解析json时遇到问题,在String中获取json响应并移入JSONArray然后解析它。但是,它说java.lang.String无法转换为JSONArray。

获取json响应的代码在doInBackground()中,在onPostExecute()中解析json。

这是我的解析代码:

public class HomeActivity extends AppCompatActivity {
    public static final int CONNECTION_TIMEOUT = 10000;
    public static final int READ_TIMEOUT = 15000;
    private RecyclerView rv_user;
    private AdapterUser mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        new AsyncFetch().execute();
    }

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

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

            pdLoading.setMessage("\tLoading...");
            pdLoading.setCancelable(false);
            pdLoading.show();

         }

         @Override
         protected String doInBackground(String... params) {
            try {
                url = new URL("https://jsonplaceholder.typicode.com/users");
            } catch (MalformedURLException e) {
                e.printStackTrace();
                return e.toString();
            }

            try {
                conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(READ_TIMEOUT);
                conn.setConnectTimeout(CONNECTION_TIMEOUT);
                conn.setRequestMethod("GET");

                conn.setDoOutput(true);

            } catch (IOException e1) {
                e1.printStackTrace();
                return e1.toString();
            }

            try {
                int response_code = conn.getResponseCode();
                if (response_code == HttpURLConnection.HTTP_OK) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    StringBuilder sb = new StringBuilder();
                    String line;

                    while ((line = reader.readLine()) != null) {
                        sb.append(line);
                    }
                    response = sb.toString();

                    // Pass data to onPostExecute method
                    System.out.println(response);

                    return (response);
                } else {
                    return ("unsuccessful");
                }

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

        @Override
        protected void onPostExecute(String result) {
            pdLoading.dismiss();
            List<DataUser> 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_user_data = jArray.getJSONObject(i);

                   DataUser userData = new DataUser();
                   userData.id = json_user_data.getString("id");
                   userData.fullName = json_user_data.getString("name");
                   userData.uName = json_user_data.getString("username");
                   userData.email = json_user_data.getString("email");

                   JSONObject addr = json_user_data.getJSONObject("address");
                   String street = addr.getString("street");
                   String city = addr.getString("city");
                   int zip = addr.getInt("zipcode");

                   userData.address = street+", "+ city + " " + zip;
                   userData.phone = json_user_data.getString("phone");
                   userData.web = json_user_data.getString("website");
                   data.add(userData);
                }

                // Setup and Handover data to recyclerview
                rv_user = (RecyclerView)findViewById(R.id.userList);
                mAdapter = new AdapterUser(HomeActivity.this, data);
                rv_user.setAdapter(mAdapter);
                rv_user.setLayoutManager(new LinearLayoutManager(HomeActivity.this));

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

        }

    }
}

请帮帮我。谢谢。

2 个答案:

答案 0 :(得分:0)

您是否从网址上看到了“结果”的内容?我想这不是你想要的。

答案 1 :(得分:0)

将代码中的两个字符串更改为:

conn.setDoOutput(false);
您将从服务器读取,而不是写入。

String zip = addr.getString("zipcode");
您的json中的邮政编码的格式为 59590-4157 ,因此无法读取为int。