安卓工作室 : Parsing JSON Data From 2 Different JSONArrays

标签 android arrays json

我有一个应用程序可以解析 JSON 数据并在回收器 View 中将其显示给用户。我要解析的 JSON 数据位于 2 个单独的数组中。在 office[] 数组中,我想显示“名称”。从 officials[] 数组中,我想显示“姓名”和“党派”。

"offices": [
 {
  "name": "President of the United States",
  "party": "Republican
 }
],
"officials": [
 {
  "name": "Donald J. Trump"
 }
]

数据应该被解析并显示为卡片 View 中的单个对象。下面是它的外观示例。 enter image description here

我的第一种方法是使用 2 个不同的 for 循环遍历每个数组,但是这种实现没有用,遗漏了官员数组中的所有数据。我通过使用嵌套的 for 循环接近了一点,但仍然显示不正确。这是我处理 JSON 解析和结果的代码。

  //fetch json data from Civic API
private void getData(){
    final ProgressDialog progressDialog = new ProgressDialog(this);
    progressDialog.setMessage("Loading...");
    progressDialog.show();

    StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            progressDialog.dismiss();
            try{
                JSONObject jsonObject = new JSONObject(response);
                //first loop through offices array. Retrieve officeName value
                JSONArray officesArray = jsonObject.getJSONArray("offices");        //One array for offices
                JSONArray officialsArray = jsonObject.getJSONArray("officials");    //one array for officials
                for (int i = 0; i < officesArray.length(); i++){
                    JSONObject jo = officesArray.getJSONObject(i);
                    Reps reps = new Reps(jo.getString("name"));
                    for (int a = 0; a < officialsArray.length(); a++){
                        JSONObject object = officialsArray.getJSONObject(a);        //nested loop
                        Reps rep = new Reps(object.getString("name"),
                                object.getString("party"));
                        repList.add(rep);
                    }
                    repList.add(reps);
                }
                /***
                //loop again this time through officials array
                for (int i = 0;  i < officialsArray.length(); i++){         //Lets see if this loop works*
                    JSONObject object = officialsArray.getJSONObject(i);       //This loop currently doesnt work. Try nested loop?
                    Reps reps = new Reps(object.getString("name"),
                            object.getString("party"));
                    repList.add(reps);
                }***/
                adapter = new RepRvAdapter(repList, getApplicationContext());
                myrv.setAdapter(adapter);
            }catch (JSONException e){
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("Volley", error.toString());
            progressDialog.dismiss();
        }
    });
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}

此代码不正确,因为它在收集第二个数组中的第一个元素之前完全遍历了第一个数组。一旦我们滚动浏览第一个数组中的所有元素,我们就可以看到第二个数组的第一个元素。 enter image description here

enter image description here

我知道我当前的实现是错误的,以及为什么信息会按原样显示,但我不确定解决方案。我当时认为将数据推送到 for 循环中的列表可能是一个问题。或者我们必须创建两个单独的 Reps 对象这一事实。这个问题最简单的解决方案是什么?让我知道您是否需要查看我的更多代码。

请求的我的适配器代码:

public class RepRvAdapter extends 
RecyclerView.Adapter<RepRvAdapter.MyViewHolder> {

private Context context;
private List<Reps> repsList;


public RepRvAdapter() {

}



public RepRvAdapter(List<Reps> repList, Context applicationContext) {
    this.repsList = repList;
    this.context = applicationContext;
}


@NonNull
@Override
public RepRvAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View view;
    LayoutInflater mInflater = LayoutInflater.from(context);
    view = mInflater.inflate(R.layout.card, viewGroup, false);         //Inflate view to card.xml
    return new MyViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull RepRvAdapter.MyViewHolder myViewHolder, int i) {
    myViewHolder.officeName.setText(repsList.get(i).getOfficeName());               //Display these three elements in the card view
    myViewHolder.officialName.setText(repsList.get(i).getOfficialName());
    myViewHolder.party.setText(repsList.get(i).getParty());
}

@Override
public int getItemCount() {
    return repsList.size();
}

public static class MyViewHolder extends RecyclerView.ViewHolder {
    //Variables
    TextView officeName, officialName, party;         //Only the Referendum title and type will be in the recycler view
    public MyViewHolder(View itemView){
        super(itemView);
        officeName = itemView.findViewById(R.id.office_name);
        officialName = itemView.findViewById(R.id.official_name);
        party = itemView.findViewById(R.id.party);
    }
}

最佳答案

您需要为您的 Reps 类创建一个可以处理单个对象中的所有 3 个值的构造函数。

Reps(String officeName, String party, String officialName) {
    //assign value from param to each property.
}

现在从 Activity 中更改您的方法,如下所示。

try {
            JSONObject jsonObject = new JSONObject(response);
            //first loop through offices array. Retrieve officeName value
            JSONArray officesArray = jsonObject.getJSONArray("offices");        //One array for offices
            JSONArray officialsArray = jsonObject.getJSONArray("officials");    //one array for officials
            for (int i = 0; i < officesArray.length(); i++) {
                JSONObject jsonoffices = officesArray.getJSONObject(i);
                JSONObject jsonofficial = officialsArray.getJSONObject(i);
                Reps reps = new Reps(jsonoffices.getString("name"), jsonoffices.getString("party"), 
                        jsonofficial.getString("name"));
                repList.add(reps);
                adapter = new RepRvAdapter(repList, getApplicationContext());
                myrv.setAdapter(adapter);
            }
        } catch (Exception Ex) {

        }

关于安卓工作室 : Parsing JSON Data From 2 Different JSONArrays,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53791417/

相关文章:

java - 从 JSON 响应中获取 String[][] 数组

JavaScript - 我正在读取 json 文件并尝试读取某个键的值

android - 如何动态调整 View 宽度和高度?

java - 在 Eclipse 中安装 Thym 时出错

android - 按值复制数组失败(使用 clone() 或 arraycopy())(Android、Java)

c++将数组索引声明为空

python - 如何使用 python 花式索引向 2D 数组添加元素?

java - 在 Java 数组中设置 boolean 值

android - 我需要为我的 Android 应用程序存储 154 张图像,最好的方法是什么?

python - 如何在python中合并多个coco json文件