-1

I have a page that contains these json data :

{
   "time": "07:08:27 AM",
   "milliseconds_since_epoch": 1425539307783,
   "date": "03-05-2015"
},
{
   "time": "07:08:27 AM",
   "milliseconds_since_epoch": 1425539307783,
   "date": "03-05-2014"
},

and this is the code I use for parsing data :

 // 1
    let urlAsString = "http://192.168.1.35/ios"
    let url = NSURL(string: urlAsString)!
    let urlSession = NSURLSession.sharedSession()

    //2
    let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
        if (error != nil) {
            println(error.localizedDescription)
        }
        var err: NSError?

        // 3
        if var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary {
        if (err != nil) {
            println("JSON Error \(err!.localizedDescription)")
        }

        // 4
        let jsonDate: String! = jsonResult["date"] as NSString
        let jsonTime: String! = jsonResult["time"] as NSString

        dispatch_async(dispatch_get_main_queue(), {
                    println(jsonDate)
        })
        }
    })
    // 5
    jsonQuery.resume()

The problem is that it only works if json data to be like this:

{
   "time": "07:08:27 AM",
   "milliseconds_since_epoch": 1425539307783,
   "date": "03-05-2015"
},

and for multiple json data it stop working.What's wrong ?

Thanks

Sandeep Chatterjee
  • 3,220
  • 9
  • 31
  • 47
user970956
  • 319
  • 1
  • 5
  • 13

1 Answers1

0

Consider validating your JSON here.

{
   "time": "07:08:27 AM",
   "milliseconds_since_epoch": 1425539307783,
   "date": "03-05-2015"
}

is a valid JSON.

enter image description here

while

{
    "time": "07:08:27 AM",
    "milliseconds_since_epoch": 1425539307783,
    "date": "03-05-2015"
},
{
    "time": "07:08:27 AM",
    "milliseconds_since_epoch": 1425539307783,
    "date": "03-05-2014"
}

is not.

enter image description here

Edit:

JSON arrays are written inside square brackets. Your JSON should be:

[
    {
        "time": "07:08:27 AM",
        "milliseconds_since_epoch": 1425539307783,
        "date": "03-05-2015"
    },
    {
        "time": "07:08:27 AM",
        "milliseconds_since_epoch": 1425539307783,
        "date": "03-05-2014"
    }
]

You can refer here and here for more details.

Sandeep Chatterjee
  • 3,220
  • 9
  • 31
  • 47