Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
583 views
in Technique[技术] by (71.8m points)

ios - json data return nil in swift

when I integrated the restful api it returns error

Optional(Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x17046c680 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.})

Can you please tell me why this happens? I coded in swift. Please check following line of code:

var jsonResponse  = NSJSONSerialization.JSONObjectWithData(ihelper.responseData!, options: NSJSONReadingOptions.AllowFragments, error: &error) as AnyObject? as? NSArray
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you don not know whether it starts with dictionary or array you better to go through the Online JSON Viewer where you can paste your json response and identify the data.

If json starts with Dictionary(Dictioanry starts with {....} in json response),you need to use

  if let jsonResponse: NSDictionary = NSJSONSerialization.JSONObjectWithData(ihelper.responseData!, options: NSJSONReadingOptions.AllowFragments, error: &error) as? NSDictionary
  {
     println("Response are(jsonResponse)")
  }

If json starts with Array(Array starts with [....] in json response),you need to use

  if let jsonResponse: NSArray = NSJSONSerialization.JSONObjectWithData(ihelper.responseData!, options: NSJSONReadingOptions.AllowFragments, error: &error) as? NSArray

  {
     println("Response are(jsonResponse)")
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...