[英]Swift - The data couldn’t be read because it isn’t in the correct format
[英]The data couldn’t be read because it isn’t in the correct format [swift 3]
我的 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 獲取 jsonString
let 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”的字典?
你是對的,因為“\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)")
}
}
我在我的日志中得到了這個:
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])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.