【问题标题】:Get specific values from JSON array从 JSON 数组中获取特定值
【发布时间】:2016-08-23 05:18:44
【问题描述】:

所以我使用 asynctask 来访问在线托管的 json 文件。我能够在我的 Android 应用程序中显示 json。现在我想显示 json 文件中的某些值。下面是我用过的json文件。

https://feeds.citibikenyc.com/stations/stations.json

例如,假设我只想显示这个 json 中的 id。我该怎么做?

protected void onPostExecute(String result) {
    super.onPostExecute(result);
    if (pd.isShowing()){
        pd.dismiss();
    }
    txtJson.setText(result);    
}

这里我在'result'中得到了完整的json值

PS:完成异步任务

   private class JsonTask extends AsyncTask<String, String, String> {

        protected void onPreExecute() {

            super.onPreExecute();

            pd = new ProgressDialog(GetJson.this);
            pd.setMessage("Please wait");
            pd.setCancelable(false);
            pd.show();

        }

        protected String doInBackground(String... params) {

            HttpURLConnection connection = null;
            BufferedReader reader = null; //BufferedReader reads text from the input stream


            try {
                URL url = new URL(params[0]); // params[0] is the first value in String..params (String..params can
                                                //have any no.of string parameters )
                connection = (HttpURLConnection) url.openConnection();
                connection.connect(); //not necessary.works without this.

                InputStream stream = connection.getInputStream();

                reader = new BufferedReader(new InputStreamReader(stream));

                StringBuffer buffer = new StringBuffer();  // A string buffer is like a String, but can be modified
                String line = "";

                while ((line = reader.readLine()) != null) {
                    buffer.append(line+"\n");
                    //Log.d("Response: ", "> " + line);   //here u ll get whole response...... :-)

                }
                //Log.d("BufferTest",buffer.toString());
                return buffer.toString();



            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
                try {
                    if (reader != null) {
                        reader.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {  //Here the 'result' is whatever that is returned from the
                                                        //doinbackground method (Ex: buffer.toString(); )


            try {
                JSONObject jsonobject = new JSONObject(result);
                JSONArray jsonarray = jsonobject.getJSONArray("stationBeanList");
                String id = "";
                for(int i =0; i<jsonarray.length();i++){

                    JSONObject jsonObject2 = jsonarray.getJSONObject(i);
                    id = jsonObject2.getString("stationName");
                    txtJson.setText(id);

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }



         super.onPostExecute(result);
            if (pd.isShowing()){
                pd.dismiss();
            }
            //txtJson.setText(result);


        }
    }

【问题讨论】:

  • 遍历stationBeanList数组并从每个jsonObject获取id
  • 你应该看看JSONObject
  • 在下面看到我的答案

标签: android json android-asynctask


【解决方案1】:

如果您需要示例,请关注this link

首先创建模型

public class StationBean{
    String id;
    String stationName;

    StationBean() {
    } 

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    } 


}

现在如果你想显示数据那么你需要使用Recycleview Adapter

public class RVAdapter extends RecyclerView.Adapter<RVAdapter.PersonViewHolder> {
    List<StationBean> StationBean;

    RVAdapter(List<StationBean> StationBean) {
        this.stationBean= StationBean;
    }

    @Override
    public StationBeanViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
        StationBeanViewHolder pvh = new StationBeanViewHolder(v);
        return pvh;
    }

    @Override
    public void onBindViewHolder(PersonViewHolder holder, int position) {
        holder.stationName.setText(stationName.get(position).stationName);

    }

    @Override
    public int getItemCount() {
        if (stationName!= null) {
            return persons.size();
        }
        return 0;
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
    }

    public static class StationNameViewHolder extends RecyclerView.ViewHolder {
        CardView cv;
        TextView stationName;


        PersonViewHolder(View itemView) {
            super(itemView);
            cv = (CardView) itemView.findViewById(R.id.cv);
            stationName = (TextView) itemView.findViewById(R.id.stationName);

        }
    }
}

然后你的Activity端写下:

    RecyclerView rv = (RecyclerView)findViewById(R.id.rv);
    rv.setHasFixedSize(true);

    LinearLayoutManager llm = new LinearLayoutManager(mContext);
    rv.setLayoutManager(llm);

    final RVAdapter rvAdapter = new RVAdapter(personList);
    rv.setAdapter(rvAdapter);


  try {
    JSONObject obj = new JSONObject(result);
    JSONArray stationBeanListJSONArray = null;
    stationBeanListJSONArray = obj .getJSONArray("stationBeanList");

    for (int i = 0; i < stationBeanListJSONArray .length(); i++) {
        StationBeanperson = new StationBean();
        JSONObject jObj =stationBeanListJSONArray .getJSONObject(i);
         person.Id = jObj.getString("id");
         person.stationName=jObj.getString("stationName");
         personList.add(i, person);
    }
    rvAdapter.notifyDataSetChanged();
  } catch (JSONException e) {
         e.printStackTrace();
  }

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    您必须使用以下代码解析结果:

     protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (pd.isShowing()) {
                pd.dismiss();
            }
            try {
                JSONObject json = new JSONObject(result);
                JSONArray jsonArray = json.getJSONArray("stationBeanList");
                String value = "";
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObj = jsonArray.getJSONObject(i);
                    value = jsonObj.getString("stationName");
                    Log.d("TAG", "stationName :" + value);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            //  txtJson.setText(result);    
        }
    

    【讨论】:

    • 这可行,但我只看到最后一个对象的值。
    • 你能用日志发布你的完整异步任务吗?
    • 我已经添加了完整的异步任务。请检查。我也调试它并检查了..它也只显示一个值。
    • JSONObject jsonObject2 = jsonarray.getJSONObject(i);这里jsonObject2只显示一条记录,也就是最后一条记录。
    • @user3852473 你的代码有错误,你不断地改变相同的文本视图数据,所以它发生了。 " txtJson.setText(id); " 写在下面 "Log.d("TAG", "stationName :" + id); " 并检查它会打印所有。
    猜你喜欢
    • 1970-01-01
    • 2022-01-20
    • 2019-10-08
    • 2019-03-30
    • 2023-03-04
    • 1970-01-01
    • 2020-06-25
    • 1970-01-01
    • 2015-06-13
    相关资源
    最近更新 更多