解析json多个url

时间:2017-07-17 20:54:34

标签: android json

我可以用这种方式解析网址中的json:

String link1 = "http://www.url.com/test1.json";
String link2 = "http://www.url.com/test2.json";
private void fetchMovies() {
    String url = link1;
    JsonArrayRequest req = new JsonArrayRequest(url,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    if (response.length() > 0) {
                        for (int i = 0; i < response.length(); i++) {
                            try {
                                JSONObject movieObj = response.getJSONObject(i);
                                int rank = movieObj.getInt("rank");
                                String title = movieObj.getString("title");
                                Movie m = new Movie(rank, title);
                                movieList.add(0, m);
                            } catch (JSONException e) {
                            }
                        }
                        adapter.notifyDataSetChanged();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
        }
    });
    MyApplication.getInstance().addToRequestQueue(req);
}

我想从多个网址解析我的json。

我想同时解析url1和url2。

我该怎么做?

2 个答案:

答案 0 :(得分:2)

我创建了一个类MyAsyncTask,该类接收URL列表和上下文活动。引导自己使用示例代码。

public class MyAsyncTask extends AsyncTask<Void, Void, List<JSONObject>> {

    private Activity activity;
    private List<String> urls;

    public MyAsyncTask(Activity activity, List<String> urls) {
        this.urls = urls;
        this.activity = activity;
    }

    @Override
    protected List<JSONObject> doInBackground(Void... voids) {
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        List<JSONObject> jsonURls = new ArrayList<>();
        try{
            for (String url : urls) {
                URL link = new URL(url);
                connection = (HttpURLConnection) link.openConnection();
                connection.setRequestProperty("Content-Type", "application/json");
                connection.setRequestMethod("GET");
                connection.connect();

                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                String line = null;
                StringBuilder sb = new StringBuilder();

                while ((line = reader.readLine()) != null)
                    sb.append(line);

                reader.close();
                JSONObject jsonResult = new JSONObject(sb.toString());
                jsonURls.add(jsonResult);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            Toast.makeText(activity, "URL error", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(activity, "Connection error", Toast.LENGTH_SHORT).show();
        } catch (JSONException e) {
            e.printStackTrace();
            Toast.makeText(activity, "JSON Parsing error", Toast.LENGTH_SHORT).show();
        }
        return jsonURls;
    }

    @Override
    protected void onPostExecute(List<JSONObject> jsonObjects) {
        super.onPostExecute(jsonObjects);
        // Process your JSONs
    }
}

要进行调用,您应该执行以下操作(在您的活动中):

List<String> urls = new ArrayList<>();
urls.add("https://jsonplaceholder.typicode.com/posts/1");
MyAsyncTask myAsyncTask = new MyAsyncTask(MyActivity.this, urls);
myAsyncTask.execute();

JSON的处理,您必须使用PostExecute方法。

不要忘记添加互联网权限。

答案 1 :(得分:0)

您可以简单地将网址添加到arraylist中,并通过循环来解析网址。

Arralist<String> arraylist = new Arraylist;
    arraylist.add(link1);
    arralist.add(link2);


 private void fetchMovies() {
        int x = arralist.size();
    for(int i = 0;i<x;i++)
      {  JsonArrayRequest req = new JsonArrayRequest(arralist.get(i),
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        if (response.length() > 0) {
                            for (int i = 0; i < response.length(); i++) {
                                try {
                                    JSONObject movieObj = response.getJSONObject(i);
                                    int rank = movieObj.getInt("rank");
                                    String title = movieObj.getString("title");
                                    Movie m = new Movie(rank, title);
                                    movieList.add(0, m);
                                } catch (JSONException e) {
                                }
                            }
                            adapter.notifyDataSetChanged();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
        MyApplication.getInstance().addToRequestQueue(req);
    }}