如果我有复杂的JSON数组,如何从模型类获取值?

时间:2018-08-31 07:01:08

标签: java android json

我正面临内部jsonarray的问题。在下面的步骤中,我将提供JSON响应和问题。请仔细查看并提供解决方案。 JSON响应:

{
        "Response": {
            "ResponseCode": 1,
            "ResponseText": "Success"
        },
        "Detail": [
            {
                "DateOfSlot": "08/31/2018",
                "AvailableTimeSlots": [
                    {
                        "TimeSlotId": 42,
                        "TimeOfSlot": "12:15 PM",
                        "TimeofSlotDateTime": "2018-08-31T12:15:00"
                    },
                    {
                        "TimeSlotId": 110,
                        "TimeOfSlot": "11:45 PM",
                        "TimeofSlotDateTime": "2018-08-31T23:45:00"
                    }
                ],
                "ScheduleId": 4203,
                "GetBlockedTimings": [
                    {
                        "DateOfSlot": "8/31/2018 12:00:00 AM",
                        "AvailableTimeSlots": null,
                        "ScheduleId": 0,
                        "GetBlockedTimings": null,
                        "BlockId": 1831,
                        "fkTimeId": 42,
                        "IsDeleted": false,
                        "fkScheduledId": 4203,
                        "utcDateOfSlot": "0001-01-01T00:00:00"
                    }
                ],
                "BlockId": 0,
                "fkTimeId": 0,
                "IsDeleted": false,
                "fkScheduledId": 0,
                "utcDateOfSlot": "2018-08-31T00:00:00Z"
            },
            {
                "DateOfSlot": "09/1/2018",
                "AvailableTimeSlots": [
                    {
                        "TimeSlotId": 112,
                        "TimeOfSlot": "12:00 AM",
                        "TimeofSlotDateTime": "2018-09-01T00:00:00"
                    },

                    {
                        "TimeSlotId": 110,
                        "TimeOfSlot": "11:45 PM",
                        "TimeofSlotDateTime": "2018-09-01T23:45:00"
                    }
                ],
                "ScheduleId": 4204,
                "GetBlockedTimings": null,
                "BlockId": 0,
                "fkTimeId": 0,
                "IsDeleted": false,
                "fkScheduledId": 0,
                "utcDateOfSlot": "2018-08-31T00:00:00Z"
            },
            {
                "DateOfSlot": "09/2/2018",
                "AvailableTimeSlots": [
                    {
                        "TimeSlotId": 112,
                        "TimeOfSlot": "12:00 AM",
                        "TimeofSlotDateTime": "2018-09-02T00:00:00"
                    },

                    {
                        "TimeSlotId": 110,
                        "TimeOfSlot": "11:45 PM",
                        "TimeofSlotDateTime": "2018-09-02T23:45:00"
                    }
                ],
                "ScheduleId": 4205,
                "GetBlockedTimings": null,
                "BlockId": 0,
                "fkTimeId": 0,
                "IsDeleted": false,
                "fkScheduledId": 0,
                "utcDateOfSlot": "2018-09-01T00:00:00Z"
            }
        ]
    }
  1. 在1个屏幕上,我正在使用3个文本视图。在这些文本视图中,我必须显示“ DateOfSlot”参数值。
  2. 在同一屏幕上,我有3个列表,其中我必须按选定的或单击的文本视图显示数据,其他将不可见。就像第一个文本视图的值为DateOfSlot": "08/31/2018那样,那么我只能在JSONObject上显示[0]列表中的“ AvailableTimeSlots” jsonarray的TimeOfSlot": "12:15 PM值。如果“ GetBlockedTimings” jsonarray不为null,那么我必须更改该值的文本颜色。对于颜色更改,我们必须比较“ fkTimeId”和“ TimeSlotId”。如果两者相等,则该行文本应更改(红色)。

 private void pastappointments() {


        final String requestBody = "'{\"UtcTimeOffset\":\"330\",\"DocId\":\"1079\"}'";

        Log.e(TAG, "Login :: " + requestBody);
        NetworkManager.getInstance(this).makeNetworkRequestForJSON(1, Request.Method.POST, Common.BASE_URL + "/PostDoctorGetDoctorSchedule", null, requestBody
                , null,
                new NetworkResponseListenerJSONObject() {
                    @Override
                    public void onDataReceived(int requestCode, Object data) {

                        Log.e(TAG, "requestCode :: " + requestCode);
                        Log.e(TAG, "data :: " + data);
                        Log.e(TAG, "Response : " + data.toString());

                        try {

                            JSONObject jsonObject = new JSONObject(data.toString());
                            JSONObject ResponseJsonObject1 = jsonObject.getJSONObject("Response");
                            int ResponseCode = ResponseJsonObject1.getInt("ResponseCode");
                            String ResponseText = ResponseJsonObject1.getString("ResponseText");

                            int j = 0;
                            AvailableTimeSlots available_slot = null;
                            if (ResponseCode == 1) {
                                JSONArray detailsJsonArray = jsonObject.getJSONArray("Detail");

//                                for (int i = 0; i < detailsJsonArray.length(); i++)
//                                {

                                JSONObject detailOneObject = detailsJsonArray.getJSONObject(0);

                                String date_one = detailOneObject.getString("DateOfSlot");
                                rb_today.setText(date_one);
                                String BlockId = detailOneObject.getString("BlockId");
                                String fkTimeId = detailOneObject.getString("fkTimeId");
                                Boolean IsDeleted = detailOneObject.getBoolean("IsDeleted");
                                int fkScheduledId = detailOneObject.getInt("fkScheduledId");
                                String utcDateOfSlot = detailOneObject.getString("utcDateOfSlot");
                                String ScheduleId = detailOneObject.getString("ScheduleId");
                                slot = new PostDoctorGetDoctorSchedule();
                                slot.setDateOfSlot(date_one);
                                slot.setBlockId(BlockId);
                                slot.setScheduleId(ScheduleId);
                                slot.setFkTimeId(fkTimeId);
                                slot.setIsDeleted(IsDeleted);
                                slot.setFkScheduledId(fkScheduledId);
                                slot.setUtcDateOfSlot(utcDateOfSlot);
                                //slot.AvailableTimeSlots = new ArrayList<>();
                                JSONArray AvailableTimeSlots = detailOneObject.getJSONArray("AvailableTimeSlots");
                                available_slot = null;
                                for (j = 0; j < AvailableTimeSlots.length(); j++) {
                                    // JSONObject AvailableTimeSlots_detailOneObject = detailsJsonArray.getJSONObject(0);
                                    JSONObject leagueData = AvailableTimeSlots.getJSONObject(j);

                                    String TimeSlotId = leagueData.getString("TimeSlotId");
                                    String TimeOfSlot = leagueData.getString("TimeOfSlot");
                                    String TimeofSlotDateTime = leagueData.getString("TimeofSlotDateTime");

                                    available_slot = new AvailableTimeSlots();
                                    available_slot.timeSlotId = Integer.parseInt(TimeSlotId);
                                    available_slot.timeOfSlot = TimeOfSlot;
                                    available_slot.timeofSlotDateTime = TimeofSlotDateTime;
                                    //slot.AvailableTimeSlots.add(available_slot);
                                    availableTimeSlotses.add(available_slot);
                                    slot.setAvailableTimeSlots(availableTimeSlotses);
                                    PostDoctorGetDoctorSchedulepojo.add(slot);
                                    pastAppointmentsAdapter = new PastAppointmentAdapter(MainActivity.this, PostDoctorGetDoctorSchedulepojo);
                                    rv_get_doctor_schedule.setAdapter(pastAppointmentsAdapter);

                                }
                                //slot.GetBlockedTimings = new ArrayList<GetBlockedTimings>();
                                JSONArray GetBlockedTimings = detailOneObject.getJSONArray("GetBlockedTimings");

//                                if (GetBlockedTimings.length() > 0 || GetBlockedTimings != null)
//                                {
                                for (int k = 0; k < GetBlockedTimings.length(); k++) {
                                    JSONObject leagueData_block = GetBlockedTimings.getJSONObject(k);
                                    String DateOfSlot = leagueData_block.getString("DateOfSlot");
                                    String AvailableTimeSlots_block = leagueData_block.getString("AvailableTimeSlots");
                                    int ScheduleId_block = leagueData_block.getInt("ScheduleId");
                                    int BlockId_block = leagueData_block.getInt("BlockId");
                                    int fkTimeId_block = leagueData_block.getInt("fkTimeId");
                                    int fkScheduledId_block = leagueData_block.getInt("fkScheduledId");
                                    String GetBlockedTimings_block = leagueData_block.getString("GetBlockedTimings");
                                    String utcDateOfSlot_block = leagueData_block.getString("utcDateOfSlot");
                                    Boolean IsDeleted_block = leagueData_block.getBoolean("IsDeleted");

                                    getblock_slot = new GetBlockedTimings();
                                    getblock_slot.setBlockId(BlockId_block);
                                    getblock_slot.setFkTimeId(fkTimeId_block);
                                    getblock_slot.setFkScheduledId(fkScheduledId_block);
                                   //  Toast.makeText(MainActivity.this,"timeid"+getblock_slot.getFkTimeId(),Toast.LENGTH_SHORT).show();

                                }
                                if (GetBlockedTimings.length() > 0 || GetBlockedTimings != null) {

                                    getBlockedTimings.add(getblock_slot);
                                    slot.setGetBlockedTimings(getBlockedTimings);
                                    Toast.makeText(MainActivity.this,"timeid"+slot.getGetBlockedTimings(),Toast.LENGTH_SHORT).show();
                                    PostDoctorGetDoctorSchedulepojo.add(slot);
                                }
                                else
                                    {
                                    Toast.makeText(MainActivity.this, "Nothing is here", Toast.LENGTH_SHORT).show();
                                }


                            }


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

                    }

                    @Override
                    public void onDataFailed(int requestCode, VolleyError error) {

                        Log.e(TAG, "requestCode :: " + requestCode);
                        Log.e(TAG, "data :: " + error);

                        String json = null;
                        NetworkResponse response = error.networkResponse;
                        if (response != null && response.data != null) {
                            switch (response.statusCode) {
                                case 400:
                                    json = new String(response.data);
                                    json = trimMessage(json, "error_description");
                                    if (json != null) displayMessage(json);
                                    break;
                            }
                            //Additional cases
                        }
                    }

                });
    }

我的适配器类代码

    @Override
    public void onBindViewHolder(final PastAppointmentsViewHolder holder, final int position) {
        final PostDoctorGetDoctorSchedule c = PostDoctorGetDoctorSchedule.get(position);
        try{
          timeofslot=c.AvailableTimeSlots.get(position).getTimeOfSlot();


            holder.tv_past_appointmentname.setText(timeofslot);
        }
        catch (NullPointerException | IndexOutOfBoundsException e) {
            e.printStackTrace();
        }



       try{
           fk_id = c.GetBlockedTimings.get(position).getFkTimeId();
           value_block=fk_id;
           Log.e("DateofSlot11122", String.valueOf(fk_id));
       }
       catch (NullPointerException | IndexOutOfBoundsException e) {
           e.printStackTrace();
       }

String fk_value= String.valueOf(fk_id);

       if(timeofslot==fk_value){
           holder.tv_past_appointmentname.setTextColor(Color.RED);
       }

      holder.ll_row_item_get_doctor_schedule.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("LongLogTag")
            @Override
            public void onClick(View v) {

                holder.btn_block1.setVisibility(View.VISIBLE);
            }
        });
        holder.btn_block1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                holder.tv_past_appointmentname.setTextColor(Color.parseColor("#ff0000"));



                final Dialog lDialog = new Dialog(context);
                lDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                lDialog.setCancelable(false);
                lDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                lDialog.getWindow().setDimAmount(.7f);
                lDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
                    lDialog.getWindow().setElevation(4);
                }

                lDialog.setContentView(R.layout.popup_no_yes);
                TextView tv_titiel = (TextView) lDialog.findViewById(R.id.tv_titiel);
                TextView textMsg = (TextView) lDialog.findViewById(R.id.popup_msgs);
                Button btnno = (Button) lDialog.findViewById(R.id.popup_no_btn);
                Button btnyes = (Button) lDialog.findViewById(R.id.popup_yes_btn);
                btnno.setTransformationMethod(null);
                btnyes.setTransformationMethod(null);
                tv_titiel.setText("Schedule");
                textMsg.setText("Are you sure you want to block this slot?");
                btnno.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        lDialog.dismiss();
                        holder.tv_past_appointmentname.setTextColor(Color.parseColor("#000000"));
                    }
                });
                btnyes.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        holder.tv_past_appointmentname.setTextColor(Color.parseColor("#ff0000"));
                        timeslot_id_value=c.AvailableTimeSlots.get(position).getTimeSlotId();
                        fkscheduleid=c.getScheduleId();
                        DateofSlot=c.getDateOfSlot();
                        Toast.makeText(context,"click_value"+timeslot_id_value + " " + fkscheduleid,Toast.LENGTH_SHORT).show();


                        slotBlockingApi();
                        lDialog.dismiss();
                    }
                });
                lDialog.show();

            }
        });
    }

2 个答案:

答案 0 :(得分:0)

this link可以帮助我们,


好,

1。我们的模型类可能像:

public class SlotInfo {
    public String dateOfSlot;
    public ArrayList<AvailableTimeSlot> availableTimeSlots;
    public long scheduleId;
    public ArrayList<GetBlockedTiming> getBlockedTimings;

    public long blockId;
    public long fkTimeId;
    public boolean isDeleted;
    public long fkScheduledId;
    public long utcDateOfSlot;
}

public class AvailableTimeSlot {
    public long timeSlotId;
    public String timeOfSlot;
    public String timeofSlotDateTime;
}

public class GetBlockedTiming {
    public String dateOfSlot;
    public ArrayList<AvailableTimeSlot> availableTimeSlots;
    public ArrayList<GetBlockedTiming> getBlockedTimings;
    public long blockId;
    public long fkTimeId;
    public boolean isDeleted;
    public long fkScheduledId;
    public long utcDateOfSlot;
}
  1. 我们应该

    ArrayList<SlotInfo> slotInfos = new ArrayList<>();
    try {
        JSONObject jSlots = new JSONObject("Your JSON String");
        JSONArray arrDetail = jSlots.getJSONArray("Detail");
    
        for(int i = 0; i < arrDetail.length(); i++) {
    
            JSONObject jSlot = arrDetail.getJSONObject(i);
    
            SlotInfo slotInfo = new SlotInfo();
    
            slotInfo.blockId = jSlot.getLong("blockId");
            slotInfo.dateOfSlot = jSlot.getString("dateOfSlot");
            slotInfo.fkScheduledId = jSlot.getLong("fkScheduledId");
            slotInfo.fkTimeId = jSlot.getLong("fkTimeId");
            // so set all top level data ...
    
            // then availableTimeSlots
            slotInfo.availableTimeSlots = new ArrayList<>();
            JSONArray arrAvailableTimeSlots = jSlots.getJSONArray("AvailableTimeSlots");
            for(int j = 0; j < arrAvailableTimeSlots.length(); j++) {
                JSONObject jAvailableTimeSlot = arrAvailableTimeSlots.getJSONObject(j);
    
                AvailableTimeSlot availableTimeSlot = new AvailableTimeSlot();
                availableTimeSlot.timeOfSlot = jAvailableTimeSlot.getString("timeOfSlot");
                // so set all data ...
    
                // and add it to
                slotInfo.availableTimeSlots.add(availableTimeSlot);
            }
    
            // then GetBlockedTimings
            slotInfo.getBlockedTimings = new ArrayList<>();
            JSONArray arrGetBlockedTimings = jSlots.getJSONArray("GetBlockedTimings");
            for(int k = 0; k < arrGetBlockedTimings.length(); k++) {
                JSONObject jGetBlockedTiming = arrAvailableTimeSlots.getJSONObject(k);
    
                GetBlockedTiming getBlockedTiming = new GetBlockedTiming();
                getBlockedTiming.blockId = jGetBlockedTiming.getLong("blockId");
                // so set all data ...
    
                // and add it to
                slotInfo.getBlockedTimings.add(getBlockedTiming);
    
            }
    
            slotInfos.add(slotInfo);
        }
    
    } catch (JSONException e) {
        e.printStackTrace();
    }
    

  1. 我们如何获取“ DateOfSlot”值并将其显示在测试框中?

假设我们在类级别定义文本视图:

    TextView tvDateOfSlot1;
    TextView tvDateOfSlot2;
    TextView tvDateOfSlot3;

所以我们可以在onCreateView中设置它们,例如:

    tvDateOfSlot1  = findViewById(R.id.tv_dateOfSlot1);
    tvDateOfSlot2  = findViewById(R.id.tv_dateOfSlot2);
    tvDateOfSlot3  = findViewById(R.id.tv_dateOfSlot3);

然后,在初始化“ slotInfos”后,我们可以设置textView值,例如:

   tvDateOfSlot1.setText(slotInfos[0].dateOfSlot);
   tvDateOfSlot2.setText(slotInfos[1].dateOfSlot);
   tvDateOfSlot3.setText(slotInfos[2].dateOfSlot);

祝你好运


祝你好运

答案 1 :(得分:0)

JsonObject mainObject = new JsonObject("Your JSON String");
JsonArray arr = mainObject.getJsonArray("Detail");

for(int i = 0; i < arr.lenght(); i++) {
    JsonObject dateOfSlotObj = arr.getJsonObject(i);
    String dateOfSlot = dateOfSlotObj.getString("DateOfSlot");//DateOfSlot field
    JsonArray availableSlotsArr = dateOfSlotObj.getJsonArray("AvailableTimeSlots");
    for(int j = 0; j < availableSlotsArr.lenght(); j++) {
        JsonObject availableSlotObj = availableSlotsArr[j];
        int timeSlotId = availableSlotObj.getInt("TimeSlotId");
        String timeOfSlot= availableSlotObj.getString("TimeOfSlot");
        String timeofSlotDateTime= availableSlotObj.getString("TimeofSlotDateTime");
    }
}

要检查GetBlockedTimings是否不为空,可以检查下一行代码

    if(!dateOfSlotObj.isNull("GetBlockedTimings")){
          //extract array and do something
    }