0
["[{\"timeFrom\":\"06:00:00\",\"timeTo\":\"09:00:00\",\"title\":\"First\"},{\"timeFrom\":\"09:00:00\",\"timeTo\":\"12:00:00\",\"title\":\"Second\"},{\"timeFrom\":\"12:00:00\",\"timeTo\":\"16:00:00\",\"title\":\"Third\"},{\"timeFrom\":\"16:00:00\",\"timeTo\":\"20:00:00\",\"title\":\"Fourth\"},{\"timeFrom\":\"20:00:00\",\"timeTo\":\"21:30:00\",\"title\":\"5th\"},{\"timeFrom\":\"21:30:00\",\"timeTo\":\"00:00:00\",\"title\":\"Dessert (within two hours of bedtime)th\"}]"]

我在记录 JSONArray 时得到了这个数组。我如何迭代它并获得这些值?

编辑

for (int i = 0; i < MyService.Meals.length(); ++i) { 
JSONObject rec = MyService.Meals.getJSONObject(i); String text = rec.getString("timeFrom"); 
}

不返回任何内容,因为 MyService.Meals.length() = 1。

MyService.Meals 是 JSONArray 实例

4

2 回答 2

1

出现问题是因为您的数组格式如下:

[
  "[{\"timeFrom\":\"06:00:00\",\"timeTo\":\"09:00:00\",\"title\":\"First\"},{\"timeFrom\":\"09:00:00\",\"timeTo\":\"12:00:00\",\"title\":\"Second\"},{\"timeFrom\":\"12:00:00\",\"timeTo\":\"16:00:00\",\"title\":\"Third\"},{\"timeFrom\":\"16:00:00\",\"timeTo\":\"20:00:00\",\"title\":\"Fourth\"},{\"timeFrom\":\"20:00:00\",\"timeTo\":\"21:30:00\",\"title\":\"5th\"},{\"timeFrom\":\"21:30:00\",\"timeTo\":\"00:00:00\",\"title\":\"Dessert (within two hours of bedtime)th\"}]"
]

这是一个大小为 1 的数组,其内容为一个字符串。

您期望字符串中的数组经过字符串编码,应该如下所示:

[
  {
    "timeFrom": "06: 00: 00",
    "timeTo": "09: 00: 00",
    "title": "First"
  },
  {
    "timeFrom": "09: 00: 00",
    "timeTo": "12: 00: 00",
    "title": "Second"
  },
  {
    "timeFrom": "12: 00: 00",
    "timeTo": "16: 00: 00",
    "title": "Third"
  },
  {
    "timeFrom": "16: 00: 00",
    "timeTo": "20: 00: 00",
    "title": "Fourth"
  },
  {
    "timeFrom": "20: 00: 00",
    "timeTo": "21: 30: 00",
    "title": "5th"
  },
  {
    "timeFrom": "21: 30: 00",
    "timeTo": "00: 00: 00",
    "title": "Dessert(withintwohoursofbedtime)th"
  }
]

检查 Javascript 代码,似乎有一个部分将您想要的数组包装在一个字符串中并将其放入另一个数组中。检查不必要的调用JSON.stringify()

于 2013-11-15T18:23:58.313 回答
0

您必须将 json 对象解析为 Java 对象,然后才能读取数据。

有关可以在 Java 中使用的函数列表,请参阅 JSON DOC 。

于 2013-11-14T21:11:46.527 回答