解析JSON对象后如何传递数据

时间:2020-08-02 11:11:01

标签: android json

我正在尝试创建一个用于组织COVID-19信息(#death,#inspection,#patiens ... etc)的应用。我找到了一个开放源代码的网站,并允许我使用JSON数据。所以我解析了它们;但是,我无法在mainActivity周围传递数据,因此可以创建图并在方法私有jsonParseRequest()之外进行计算。

这是整个jsonParseRequest方法,因此我可以请求json并对其进行解析。

我尝试过的事情:

  • 我试图使该方法使用json作为字符串返回Integer.toString() (int ndeaths, int ninspections, int npatients)数据

  • 正在创建arrayList,并添加这些数据,但是当我尝试访问它时,显示错误IndexOutOfBounds

    private void jsonParseRequest(){
        final TextView textView = (TextView) findViewById(R.id.textView);
        String url = "https://www.stopcovid19.jp/data/covid19japan.json";
        RequestQueue queue = Volley.newRequestQueue(this);
    
        final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    //Input the jsonObject to String called data
                    String data = response.toString();
                    //Create jsonObject and input the string data inside, so now the string data is converted to jsonObject?
    
                    JSONObject jsonObject = new JSONObject(data);
                    //Use json data to extract the data using the key such as "ndeaths"
                    int ndeaths = jsonObject.getInt("ndeaths");
                    int ninspections = jsonObject.getInt("ninspections");
                    int npatients = jsonObject.getInt("npatients");
                    String lastUpdate = jsonObject.getString("lastUpdate");
    
                    //the textView has to be converted to String ot be able to display!!
                    textView.setText("Last Update: " + lastUpdate + "\n" + "Number of deaths: " + Integer.toString(ndeaths) + "\n" + "Number of Inspection: " + Integer.toString(ninspections) + "\n" + "Number of Positives: " + Integer.toString(npatients));
    
    
    
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });
        queue.add(jsonObjectRequest);
    }
    

0 个答案:

没有答案