Reputation: 231
["[{\"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\"}]"]
I got this array when I log JSONArray. How can I iterate over it and get those values ?
edit
for (int i = 0; i < MyService.Meals.length(); ++i) {
JSONObject rec = MyService.Meals.getJSONObject(i); String text = rec.getString("timeFrom");
}
Doesn't return anything because MyService.Meals.length() = 1.
MyService.Meals is JSONArray instance
Upvotes: 0
Views: 1784
Reputation: 690
The issue arises because the format of your array is as follows:
[
"[{\"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\"}]"
]
Which is an array of size one, with one string as its content.
You are expecting the array inside the string that has been string-encoded, which should look like this:
[
{
"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"
}
]
Inspect the Javascript code, it seems like there is a section that is wrapping the array you want inside a string and putting that in another array. Inspect for an unnecessary call to JSON.stringify()
Upvotes: 1
Reputation: 3933
You have to parse the json object to a Java object, then you can read the data.
See the JSON DOC for a list of functions you can use in Java.
Upvotes: 0