如何从 json 数组访问单个 json 对象?

How to access invidual json objects from a json array?

我有以下响应,我想在单个 TextView 中显示所有 eqid,但我不知道如何实现, 下面是我的代码片段和响应,用于从服务器获取数据并显示在文本视图中。
谁能帮我解决这个问题?

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

    },
    {
      "eqid":"c000905e",

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

    },
    {
      "eqid":"c00090da",

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

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

    },
    {
      "eqid":"a00043nx",

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

    },

  ]
}

代码

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

您有一个 JSON 对象,其中包含一个 JSON 数组。因此,您首先从对象中检索数组,然后您可以遍历它以检索所有项目。在下面的代码中,我假设您在数组中有指定的 TextView 个对象。

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

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