Data could not be read because it is not in the correct format [swift 3]

I have json data that have json string (value) that look like this:

{ "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\"}", } 

I accept jsonString using swiftyjson

 let value = sub["Value"].string ?? "" 

After that, I convert this jsonString into a dictionary with this code below, but it always shows this error message. 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)") } } 

I think this is because "\ n", how to convert jsonstring to a dictionary that has "\ n"?

+5
source share
1 answer

You are right, the problem arose because of "\ n". I tried your code without "\ n" and it works fine.

I replaced "\ n" with "\\ n", and iOS seems to convert the string to a dictionary:

 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)") } } 

I got this in my journal:

 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]) 
+4
source

Source: https://habr.com/ru/post/1263395/


All Articles