Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无法读取Swift中的JSON元素_Json_Swift_Swift3 - Fatal编程技术网

无法读取Swift中的JSON元素

无法读取Swift中的JSON元素,json,swift,swift3,Json,Swift,Swift3,我使用的是Swift 3.0,似乎无法解析这个JSON响应 { "books": [{ "name": "NAME", "key": "Key" }], "count": 1 } 这是我正在使用的 let booksData = try JSONSerialization.jsonObject(with: data!) as! [String:Any] if let bookCount = booksData["count"] as?

我使用的是Swift 3.0,似乎无法解析这个JSON响应

{
    "books": [{
        "name": "NAME",
        "key": "Key"
    }],
    "count": 1
}
这是我正在使用的

let booksData = try JSONSerialization.jsonObject(with: data!) as! [String:Any]

if let bookCount = booksData["count"] as? String {
    print("found")
}
else {
    print("Not Found")
}
我一定错过了一些很明显的东西。我正在尝试在读取书籍数组之前读取计数。

如果let bookCount=bookData,则应为如果let bookCount=bookData,则尝试以下操作:

if let bookCount = booksData["count"] as? NSNumber {
    print("found")
} else {
    print("Not Found")
}

在JSON数据中,请参见计数:1。值1是一个JSON编号,通过JSONSerialization将其转换为NSNumber。那么作为呢?从NSNumber到String的转换总是失败。

很抱歉,这是问题中的一个输入错误;适当地编辑了问题为什么要将JSON对象强制转换为字符串数组?还有,你到底得到了什么错误?@sumneevans,因为JSON是String:Any类型的键值对。只是找不到书数。如果书不存在,它会被发现,但是如果书存在,它就不会被发现。请包含您收到的错误消息。我刚刚发现了它,并返回到SO,写下我是多么的白痴。谢谢你的回答。@HPatel,也许在发帖前放松半个小时是个不错的练习。祝你和你的应用程序好运。