user616076 user616076 - 1 year ago 52
Swift Question

When parsing JSON data from web service, no data returned

I'm trying to populate a UITableView from the results from a call to a web service. The data is returned in JSON format as below

[{"name":"CONTROL TEST",
"nc_lead":"TOM SMITH",
"dateTimeCreated":"2016-01-29 13:16:50",
[{"dateTime":"2016-02-02 11:26:18",
"statusChangeDateTime":"2016-02-02 00:00:00",
"info":"state changed to 'Y'",
{“dateTime":"2016-02-02 10:54:34",
"statusChangeDateTime":"2016-02-02 10:54:00",
"info":"T Smith changed area.",

There is no key as the first part is formed by 12 values as a header and then the logs form an array of values for each header. I return my JSON object using the code below, parsing the data object from my web service call.

let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)

I can see the return value for data using the code below

let str = NSString(data: data!, encoding: NSUTF8StringEncoding)

then I've tried using code such as the code below to extract a value for 'name' but it doesn't work

if let name = json["name"] as? [[String: AnyObject]] {}

How can I iterate through my json object to get the data from the header and the logs array?

Answer Source

It seems json object is an array of dictionary, so you should do something like this:

if let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments) as? Array<Dictionary<String, AnyObject>> {
    for item in json {
        if let dict = item as? Dictionary<String, AnyObject> {

The conversion should be to AnyObject because sometimes the value is String, like for example dict["name"] == "CONTROL TEST", but dict["logs"] is Array<Dictionary<String, String>>. Do you see it?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download