Ald*_*rdi 12 json nsdictionary ios swift swift3
我的json数据有json字符串(值),看起来像这样
{
"Label" : "NY Home1",
"Value" : "{\"state\":\"NY\",\"city\":\"NY\",\"postalCode\":\"22002\",\"value\":\"Fifth Avenue1\nNY NY 22002\nUSA\",\"iosIdentifier\":\"71395A78-604F-47BE-BC3C-7F932263D397\",\"street\":\"Fifth Avenue1\",\"country\":\"USA\"}",
}
Run Code Online (Sandbox Code Playgroud)
我使用swiftyjson获取jsonString
let value = sub["Value"].string ?? ""
Run Code Online (Sandbox Code Playgroud)
之后,我将此jsonString转换为Dictionary,使用下面的代码,但它始终显示此错误消息 The data couldn’t be read because it isn’t in the correct format
if let data = value.data(using: String.Encoding.utf8) {
do {
let a = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
print("check \(a)")
} catch {
print("ERROR \(error.localizedDescription)")
}
}
Run Code Online (Sandbox Code Playgroud)
我认为这是因为"\n",如何将jsonstring转换为具有"\n"的字典?
你是对的,问题是因为"\n"而发生的.我尝试了没有"\n"的代码,它完美无缺.
我将"\n"替换为"\\n",iOS似乎将字符串转换为字典:
let value = "{\"state\":\"NY\",\"city\":\"NY\",\"postalCode\":\"22002\",\"value\":\"Fifth Avenue1\nNY NY 22002\nUSA\",\"iosIdentifier\":\"71395A78-604F-47BE-BC3C-7F932263D397\",\"street\":\"Fifth Avenue1\",\"country\":\"USA\"}"
if let data = value.replacingOccurrences(of: "\n", with: "\\n").data(using: String.Encoding.utf8) {
do {
let a = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as? [String: Any]
NSLog("check \(a)")
} catch {
NSLog("ERROR \(error.localizedDescription)")
}
}
Run Code Online (Sandbox Code Playgroud)
我在日志中得到了这个:
check Optional(["value": Fifth Avenue1
NY NY 22002
USA, "country": USA, "city": NY, "iosIdentifier": 71395A78-604F-47BE-BC3C-7F932263D397, "street": Fifth Avenue1, "postalCode": 22002, "state": NY])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22627 次 |
| 最近记录: |