【问题标题】:Swift/Cocoa json parse error?Swift/Cocoa json 解析错误?
【发布时间】:2014-08-19 00:56:37
【问题描述】:

Swift/iphone 开发新手...

如果我在 json 中有一个字符串,它是一个 obj 数组,它可以以括号“[”开头。根据 json 规范,afaik,这没关系。但是,以下内容在 swift/xcode 中作为单元测试会爆炸:

var json = "[{\"class\":\"ProductDesign\"},{\"class\":\"ProductDesign\"}]"
let jsonObject : AnyObject! = NSJSONSerialization.JSONObjectWithData(json.dataUsingEncoding(NSUTF8StringEncoding), options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

我已经看到有人在博客上写过这样的文章,但它对我不起作用(xcode 做了一些有趣的事情,突然出现:

0x287784:  je     0x28778d                  ; swift_dynamicCastObjCClassUnconditional + 61
0x287786:  addl   $0x10, %esp
0x287789:  popl   %esi
0x28778a:  popl   %edi
0x28778b:  popl   %ebp
0x28778c:  retl   
0x28778d:  leal   0xea35(%esi), %eax
0x287793:  movl   0x468ef(%esi), %ecx
0x287799:  movl   %eax, 0x8(%ecx)
0x28779c:  movl   $0x0, 0xc(%ecx)
0x2877a3:  int3   
0x2877a4:  nopw   %cs:(%eax,%eax)

有什么想法吗?此版本中的错误?程序员愚蠢?

【问题讨论】:

  • 请访问 json.org 并花 5-10 分钟来学习 JSON。这样你就可以更实际地编写你理解的代码,而不是盲目地复制你不理解的代码。
  • 哇,先生,您刚刚赢得了 imo 混蛋的名声。感谢那些帮助我理解的人。

标签: json xcode swift


【解决方案1】:

您的 JSON 是一个数组,但您将 NSJSONSerialization.JSONObjectWithData 的结果转换为 NSDictionary;将其转换为 NSArray

let jsonObject : AnyObject! = NSJSONSerialization.JSONObjectWithData(json.dataUsingEncoding(NSUTF8StringEncoding), options: NSJSONReadingOptions.MutableContainers, error: nil) as NSArray

注意: 您也可以排除 AnyObject! 类型声明,然后这样做:

let jsonObject = NSJSONSerialization.JSONObjectWithData(json.dataUsingEncoding(NSUTF8StringEncoding), options: NSJSONReadingOptions.MutableContainers, error: nil) as NSArray

【讨论】:

  • 为了避免以后出现此类问题,您可以使用可选转换(as? 而不是as
  • 谢谢大家。一旦你告诉我就很明显了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-25
  • 1970-01-01
  • 2023-04-06
相关资源
最近更新 更多