-1

I have the following JSON file:

{ "_id" : { "$oid" : "54feffe1412807551c90eaa2"} , "loc" : [ 35.09 , 12.01]},
{ "_id" : { "$oid" : "54ff0b62412807551c90eaa4"} , "loc" : [ 43.98 , 12.34]}

How can I parse this JSON file in Swift? I need the values in loc.

Unheilig
  • 16,196
  • 193
  • 68
  • 98
ruby4newb
  • 11
  • 6

2 Answers2

0

I have the problem, that I get a fatal error: unexpectedly found nil while unwrapping an Optional value.

I send a http request to my server. Like this

        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
        if error == nil {
            var datastring:String = NSString(data:data, encoding:NSUTF8StringEncoding)!
//          println(datastring)

            if (data != nil) {
                var json=NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: &self.err) as NSDictionary
                println(json)

                if (error != nil) {
                    println(self.err?.localizedDescription)
                } else {
                  //do something here with json
                    }
                }
            } else {
                println(error.localizedDescription)
            }

and get this json file:

{ "_id" : { "$oid" : "54feffe1412807551c90eaa2"} , "loc" : [ 35.09 , 12.01]},
{ "_id" : { "$oid" : "54ff0b62412807551c90eaa4"} , "loc" : [ 43.98 , 12.34]}

If I have only one file it works. But with two files I get the fatal error.

ruby4newb
  • 11
  • 6
  • it seems that my json file is not a valid json. – ruby4newb Mar 11 '15 at 00:20
  • Yes, Format is wrong. Please check on online validator tool. And For JSON you have pasted just put square braces on start and end. –  Mar 11 '15 at 10:14
-1

Use NSJSONSerialization:

func ParseJSONData(data: NSData) -> NSDictionary? {
    if let dict = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as? NSDictionary { return dict }

    println("Failed to parse")
    return nil
}

// *********************

if let info = ParseJSONData(jsonstring.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false))
Arbitur
  • 38,684
  • 22
  • 91
  • 128