gpt4 book ai didi

json - Swift/Cocoa json 解析错误?

转载 作者:行者123 更新时间:2023-11-28 11:22:58 25 4
gpt4 key购买 nike

Swift/iphone 开发新手......

如果我在 json 中有一个字符串,它是一个 objs 数组,它可以以方括号 '[' 开头。根据 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 是一个数组,但您正在将 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

关于json - Swift/Cocoa json 解析错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25374191/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com