【问题标题】:Access JSON array inside another json array访问另一个 json 数组中的 JSON 数组
【发布时间】:2016-07-27 12:45:14
【问题描述】:

我收到这样的回复:

{
      "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 数组。

【问题讨论】:

  • 它看起来像是一个字符串数组,而不是 json 数组。向我们展示您的模型类。

标签: java arrays json response


【解决方案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);
    }
}

【讨论】:

    【解决方案2】:

    您可以使用 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();
            }
    
        }
    }
    

    输出:
    感兴趣的日子:星期一
    感兴趣的日子:星期二
    感兴趣的日子:星期一
    感兴趣的日子:星期二
    感兴趣的日子:星期四

    【讨论】:

      猜你喜欢
      • 2021-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-08
      • 2017-05-18
      • 1970-01-01
      • 2020-11-25
      • 1970-01-01
      相关资源
      最近更新 更多