How to access invidual json objects from a json array?

て烟熏妆下的殇ゞ 提交于 2019-12-11 03:33:19

问题


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();
}


来源:https://stackoverflow.com/questions/31355629/how-to-access-invidual-json-objects-from-a-json-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!