我的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\"}",
}
我使用swiftyjson
获取jsonStringlet value = sub["Value"].string ?? ""
之后我将此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)")
}
}
我认为这是因为" \ n",如何将jsonstring转换为具有" \ n" ?
答案 0 :(得分:6)
你是对的,问题是因为" \ n"而发生的。我试过你的代码没有" \ n"它的工作非常完美。
我更换了#34; \ 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)")
}
}
我在日志中获得了这个:
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])