0

I have a php file which create a JSON array. This the JSON output.

[{"employee_id":"1","employee_name":"Steve","employee_designation":"VP","employee_salary":"60000"},{"employee_id":"2","employee_name":"Robert","employee_designation":"Executive","employee_salary":"20000"},{"employee_id":"3","employee_name":"Luci","employee_designation":"Manager","employee_salary":"40000"},{"employee_id":"4","employee_name":"Joe","employee_designation":"Executive","employee_salary":"25000"},{"employee_id":"5","employee_name":"Julia","employee_designation":"Trainee","employee_salary":"10000"}]

I want to parse this array using swift in my app. So I used the following code to parse the JSON array

    func jsonParser() {
    let urlPath = "xxxxxxxxx/dbretrieve.php"
    guard let endpoint = NSURL(string: urlPath) else { print("Error creating endpoint");return }
    let request = NSMutableURLRequest(URL:endpoint)
    NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) -> Void in
        do {
            guard let dat = data else { throw JSONError.NoData }
            guard let json = try NSJSONSerialization.JSONObjectWithData(dat, options:.AllowFragments) as? NSArray else { throw JSONError.ConversionFailed }
            print(json)
        } catch let error as JSONError {
            print(error.rawValue)
        } catch {
            print(error)
        }
        }.resume()
}

but I get the following error

Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}

What's the mistake I made?

Lee
  • 850
  • 11
  • 23
ReB
  • 107
  • 10
  • [This](http://stackoverflow.com/a/25986715/730701) might be helpful. – Adam Mar 29 '16 at 10:08
  • @Adam I think the code in Objective-C and they use AFNetworking – ReB Mar 29 '16 at 10:12
  • 1
    Yes, but it doesn't matter. The error is the same and the reason is also most likely the same. It is related to serialization and has nothing to do with networking. And `NSJSONSerialization`, like every other `Cocoa (Touch)` framework works exactly the same in Swift as it does with Objective-C. – Adam Mar 29 '16 at 10:18
  • The JSON you show here is correct, but given the error message you get, the data you fetch is *not* the same and is invalid. Check that your "xxxxxxxxx/dbretrieve.php" endpoint generates JSON correctly. – Eric Aya Mar 29 '16 at 10:23
  • @EricD I debug the code and the endpoint shows that 'unable to read data'. What's the issue? – ReB Mar 29 '16 at 10:35
  • Well now it's a different question, since it's about an issue with your PHP server and not about the Swift client, isn't it? So you should ask a *new question* about your server (you can always mention this question link in the new question if necessary to give context). – Eric Aya Mar 29 '16 at 10:44
  • 1
    Debugging client-server communications is easiest if you sniff the traffic using an HTTP proxy. I use [Charles Proxy](http://charlesproxy.com) and that always immediately tells me if the issue is with my app code or with my server code. – dirkgroten Mar 29 '16 at 10:47
  • Create a breakpoint, and check your response data, that you get from the server - before the Serialization (print doesn't help - check the data byte by byte in the debugger). I had a similar issue, when PHP added some "invisible" whitespaces at the begining of the Json. – Dejan Skledar Mar 29 '16 at 11:32

1 Answers1

-1

I checked your json array. Its perfect. The point where the issue might be serialization.

  1. Depends on data you get in response
  2. Try to disable debugging mode in PHP
  3. Try below serialisation code

Sample Code:

  do {
      let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as! [String: AnyObject]

      print(json)

} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
Abdul Yasin
  • 3,480
  • 1
  • 28
  • 42