访问另一个json数组中的JSON数组

时间:2016-07-27 12:45:14

标签: java arrays json response

我收到这样的回复:

{
      "status": "Success",
      "data": [{
          "careTypeId": "10",
          "careTypeName": "Vacation Care",
          "daysOfinterest": ["Monday", "Tuesday"],
          "childDaysOfInterestId": "212"
      }, {
          "careTypeId": "10",
          "careTypeName": "Vacation Care",
          "daysOfinterest": ["Monday", "Tuesday", "Thursday"],
          "childDaysOfInterestId": "202"
      }],
      "message": "ChildDaysOf Interest"
  }

在此响应中,我需要访问数据数组,然后我需要获取daysOfInterest数组。

2 个答案:

答案 0 :(得分:1)

首先得到数据阵列 jj是你的json对象

JSONArray RecordList = new JSONArray(jj.getString("data"));
for (int i = 0; i < RecordList.length(); i++) {
                        JSONObject list = RecordList.getJSONObject(i);
                         JSONArray RecordList1 = new JSONArray(list.getstring("daysOfinterest"));
Log.e("Test" , "get Result" + RecordList1);
    }
}

答案 1 :(得分:0)

您可以使用org.json库,详细了解here

首先,您必须将jsonString转换为JSONObject,然后从JSONObject获取数据数组,然后您必须在该数组上循环以获取daysOfInterest数组。

示例代码:

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Example {

    public static void main(String[] args) {
        String jsonString = "{\n\"status\": \"Success\",\n\"data\": [{\n\"careTypeId\": \"10\",\n\"careTypeName\": \"Vacation Care\",\n\"daysOfinterest\": [\"Monday\", \"Tuesday\"],\n\"childDaysOfInterestId\": \"212\"\n}, {\n\"careTypeId\": \"10\",\n\"careTypeName\": \"Vacation Care\",\n\"daysOfinterest\": [\"Monday\", \"Tuesday\", \"Thursday\"],\n\"childDaysOfInterestId\": \"202\"\n }],\n\"message\": \"ChildDaysOf Interest\"\n }";
        try {
            JSONObject mainJsonObject = new JSONObject(jsonString);
            JSONArray dataArray = mainJsonObject.getJSONArray("data");
            for (int i = 0; i < dataArray.length(); i++) {
                JSONObject jsonObject = dataArray.getJSONObject(i);
                JSONArray daysOfInterestArray = jsonObject.getJSONArray("daysOfinterest");
                for (int j = 0; j < daysOfInterestArray.length(); j++) {
                    System.out.println("Days of interest : " + daysOfInterestArray.get(j));
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}

输出:
感兴趣的天数:星期一 感兴趣的天数:星期二 感兴趣的天数:星期一 感兴趣的天数:星期二 感兴趣的天数:星期四