How to access invidual json objects from a json ar

2019-07-22 20:42发布

问题:

I have the following response, and I want to display all eqid's in invidual TextView's, but I don't know how to achive this, below is my snippet code and response to get data from the server and display in textview.
Can anyone help me with this?

{
  "earthquakes":[
    {
      "eqid":"c0001xgp",

    },
    {
      "eqid":"c000905e",

    },
    {
      "eqid":"2007hear",

    },
    {
      "eqid":"c00090da",

    },
    {
      "eqid":"2007aqbk",

    },
    {
      "eqid":"2007hec6",

    },
    {
      "eqid":"a00043nx",

    },
    {
      "eqid":"2010utc5",

    },

  ]
}

Code

   ServiceHandler sh = new ServiceHandler();
    jsonStr = sh.makeServiceCall(USER_URL, ServiceHandler.GET);
    Log.d("Response: ", "> " + jsonStr);

    try{
        JSONObject json = new JSONObject(jsonStr);
        JSONArray items = json.getJSONArray("product");

        parent_layout = (RelativeLayout)findViewById(R.id.rl);
        for(int i =0; i<items.length(); i++){



            TextView textView = new TextView(this);
            textView.setText(items.getJSONObject(i).getString(USER_NAME));

            parent_layout.addView(textView);
        }

回答1:

try{
    JSONObject json = new JSONObject(jsonstr);
    JSONArray items = json.getJSONArray("earthquakes");

    for(int i =0; i<items.length(); i++){
        TextView t=new TextView(context);
        t.setText(items.getJSONObject(i).getString('eqid'));
        ParentLayout.addView(t);
    }
}catch(JSONException e){
    e.printStacktrace();
}



回答2:

You have a single JSON object which contains a Single JSON array. So you first retrieve the array from the object and then you are able to loop over it to retrieve all the items. In below code I assume you have the destined TextView objects in an array.

try{
    JSONObject json = new JSONObject(jsonstr);
    JSONArray items = json.getJSONArray("earthquakes");

    for(int i =0; i<items.length(); i++){
        textViews[i].setText(items.getJSONObject(i).getString('eqid'));
    }
}catch(JSONException e){
    e.printStacktrace();
}