简体   繁体   English

json数据在swift中返回nil

[英]json data return nil in swift

when I integrated the restful api it returns error当我集成restful api时它返回错误

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.})可选(错误域=NSCocoaErrorDomain 代码=3840“操作无法完成。(Cocoa 错误 3840。)”(JSON 文本未以数组或对象开头,并且选项允许未设置片段。) UserInfo=0x17046c680 {NSDebugDescription= JSON 文本未以数组或对象开头,并且没有设置允许片段的选项。})

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

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.如果您不知道它是以字典还是数组开头,您最好浏览在线 JSON 查看器,您可以在其中粘贴 json 响应并识别数据。

If json starts with Dictionary(Dictioanry starts with {....} in json response),you need to use如果json以Dictionary开头(Dictioanry在json响应中以{....}开头),则需要使用

  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如果 json 以 Array 开头(在 json 响应中数组以 [....] 开头),则需要使用

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM