Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The data couldn’t be read because it isn’t in the correct format [swift 3]

I've json data that have json string(value) that 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 take the jsonString using swiftyjson

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

After that I convert this jsonString to Dictionary with this below code but it always show 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 happen because "\n", how to convert jsonstring to dictionary that have "\n" ?

like image 495
Aldo Lazuardi Avatar asked Jan 26 '17 14:01

Aldo Lazuardi


1 Answers

You're right, problem occurred because of "\n". I tried your code without "\n" and it's work perfectly.

I replaced "\n" by "\\n", and iOS seems to convert the string to 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 obtained this in my log :

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])
like image 147
EPerrin95 Avatar answered Nov 14 '22 08:11

EPerrin95