JSONSerialization.jsonObject 返回 nil
Posted
技术标签:
【中文标题】JSONSerialization.jsonObject 返回 nil【英文标题】:JSONSerialization.jsonObject returns nil 【发布时间】:2019-03-14 00:30:18 【问题描述】:var responseString = String(data: data, encoding: .utf8)
var responseDict: [AnyHashable : Any]? = nil
if let anEncoding = responseString?.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
responseDict = try! JSONSerialization.jsonObject(with: anEncoding, options: .mutableContainers) as? [AnyHashable : Any]
responseString 即将推出:
[\"message_id\":1916,\"in_app\":\"primary_color\":\"#333333\",\"secondary_color\":\"#ffffff\",\"position\ ":\"0\",\"持续时间\":\"30\",\"到期\":\"2018-11-07T23:17:46.169-05:00\",\"delay_minute\": \"0\",\"delay_second\":\"0\",\"message\":\"这个 是您的信息的样子!在文本中输入您的消息 区域并获得预览权 这里\",\"data\":,\"deeplinkurl\":\"\",\"attachment-url\":\"\",\"title\":\"\",\" subtitle\":\"\",\"message_id\":1920,\"in_app\":\"primary_color\":\"#333333\",\"secondary_color\":\"#ffffff \",\"position\":\"0\",\"duration\":\"30\",\"expiry\":\"2018-11-08T03:52:15.404-05:00\" ,\"delay_minute\":\"0\",\"delay_second\":\"0\",\"message\":\"这个 是您的信息的样子!在文本中输入您的消息 区域并获得预览权 这里\",\"data\":,\"deeplinkurl\":\"\",\"attachment-url\":\"\",\"title\":\"\",\"副标题\":\"\"]
responseDict 即将成为nil
。
对应的Objective-C
代码运行良好。
【问题讨论】:
如果您使用 Swift 4,最好使用Codable
协议
那是因为[AnyHashable : Any]
是一个字典,但你的 JSON 是一个***数组。此外,避免使用 Swift 字典/数组的 .mutableContainers
。还有String.Encoding(rawValue: String.Encoding.utf8.rawValue)
=> .utf8
或String.Encoding.utf8
。应该够了。
@Larme 您应该将其发布为答案
@Scriptable 关于 Swift/Objective-C 中 JSON 解析的问题太多了,至少应该有一个重复,因为作者没有看到响应的***类型。
如果你的变量不是编码,为什么你的变量叫做anEncoding
?
【参考方案1】:
这很好用……
let json = """
[\"message_id\":1916,\"in_app\":\"primary_color\":\"#333333\",\"secondary_color\":\"#ffffff\",\"position\":\"0\",\"duration\":\"30\",\"expiry\":\"2018-11-07T23:17:46.169-05:00\",\"delay_minute\":\"0\",\"delay_second\":\"0\",\"message\":\"This is what your message will look like! Type in your message in the text area and get a preview right here\",\"data\":,\"deeplinkurl\":\"\",\"attachment-url\":\"\",\"title\":\"\",\"subtitle\":\"\",\"message_id\":1920,\"in_app\":\"primary_color\":\"#333333\",\"secondary_color\":\"#ffffff\",\"position\":\"0\",\"duration\":\"30\",\"expiry\":\"2018-11-08T03:52:15.404-05:00\",\"delay_minute\":\"0\",\"delay_second\":\"0\",\"message\":\"This is what your message will look like! Type in your message in the text area and get a preview right here\",\"data\":,\"deeplinkurl\":\"\",\"attachment-url\":\"\",\"title\":\"\",\"subtitle\":\"\"]
""".data(using: .utf8)!
do
let object = try JSONSerialization.jsonObject(with: json, options: [])
print(object)
catch
print(error)
...但不要使用JSONSerialization
...声明代表您的数据的自定义对象并改用Decodable
【讨论】:
请注意,由于缺少as? Dictionary
,因此该解决方案有效,与问题中的代码相反。 as? [[String: Any]]
也应该有工作。以上是关于JSONSerialization.jsonObject 返回 nil的主要内容,如果未能解决你的问题,请参考以下文章