gpt4 book ai didi

json - NSJSONSerialization 解析错误

转载 作者:行者123 更新时间:2023-11-30 13:57:49 25 4
gpt4 key购买 nike

我在尝试从 URL 解析 JSON 时遇到错误。

代码如下:

      override func viewDidLoad() {  
super.viewDidLoad()
print("hello")
let url=NSURL(string:"http://jsonReports/sample_testkrtk252.json")
print("hello2")

if let allContactsData=NSData(contentsOfURL:url!)

{
print(allContactsData)
do{
let allContacts: AnyObject! = try NSJSONSerialization.JSONObjectWithData(allContactsData, options: NSJSONReadingOptions.MutableContainers)
print(allContacts)
if let json = allContacts as? Array<AnyObject> {

print(json)
for index in 0...json.count-1 {

let data12 : AnyObject? = json[index]
print(data12)

let collection = data12! as! Dictionary<String, AnyObject>
print(collection)

print(collection["data11"])

let data11 : AnyObject? = collection["data11"]
let cont : AnyObject? = collection["cont"]

data1.append(data11 as! String)
data2.append(cont as! String)

print(data1)
print(data2)
}
}
}
catch
{
print("error")
}
}

成功运行后,它会给出以下输出:

hello
hello2
<7b0d0a20 20202022 ... >
error
(lldb)

此外,它还给出了错误:

NSError Domain: "NSCocoaErrorDomain" - code: 3840 0x00007f8b62c9ef50 _userInfo __NSDictionaryI * 1 key/value pair 0x00007f8b62dcb3c0

如果有人能研究一下这个问题那就太好了。另外,有没有更好的方法在 Swift 中解析 JSON?

最佳答案

您的文件 .json 不是有效的结构。删除第一行:

"registration_id":APA91bEVsOgzkFFDCuEFn8PAS-FQqeaW6TRuz09CeKSnAJUSJmTvP8ubIsUkUe2zOzz8vk-FNqbNteOcD6m8m5nhrNWA96swZHYyX4nvY-mPCJTeBkEXTLuLwWCglbAUVCqJlwharLLJ,

现在尝试运行代码:

 func run()->(Void){
//insert you file .jso into project. Or change the code
let filePath = NSBundle.mainBundle().pathForResource("sample_testkrtk252", ofType:"json")
let nsMutData:NSData = NSData(contentsOfFile:filePath!)!
do{
let allContacts:[String:AnyObject] = try NSJSONSerialization.JSONObjectWithData(nsMutData, options: NSJSONReadingOptions.MutableContainers) as! [String : AnyObject]
print(allContacts)

for temp in 0...allContacts.count-1 {

print(temp)
}

} catch
{
print("error")

}
}

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

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