简体   繁体   中英

parse json with URL which contains double quotes - swift

I am tring to decode json with URL value which contains double quotes but I am always getting "The given data was not valid JSON." or "Invalid URL String." error while decoding the object.

let data = Data("""{ "contentUrl":"https://somedomain.come/folder/1-test_Romio's-\"Video-?hl=en-GB" }
""".utf8)


do {
    let decoder = JSONDecoder()
    let object = try decoder.decode(Model.self, from: data)

    print(object)
} catch {
    print(error)
}


struct Model: Codable {
    let contentUrl: URL
}

How can I escape this double quotes in the url, given that the url is generated based on user input so the user can enter " double quotes ?

The JSON spec asks that double quotes in strings be preceded by a backslash.

In Swift this string

"aString \" With a Double Quote" 

has a double quote with no backslash in front of it.

To get a string that has a backslash and a quote it would have to be:

"aString \\\" With a Double Quote"

You should change your sample to:

"{ "contentUrl":"https://somedomain.come/folder/1-test_Romio's-\\\"Video-?hl=en-GB" }"

That will make it valid JSON, though it still won't be valid URL. To be a valid URL you have to escape the double quotes using percent escape encoding

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM