[英]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."我正在尝试使用包含双引号的 URL 值解码 json,但我总是收到“给定的数据不是有效的 JSON”。 or "Invalid URL String."或“无效的 URL 字符串”。 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 ?考虑到 url 是根据用户输入生成的,因此用户可以输入 " 双引号,如何在 url 中转义这个双引号?
The JSON spec asks that double quotes in strings be preceded by a backslash. JSON 规范要求字符串中的双引号前面加上反斜杠。
In Swift this string在 Swift 中这个字符串
"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.这将使它成为有效的 JSON,尽管它仍然不是有效的 URL。 To be a valid URL you have to escape the double quotes using percent escape encoding要成为有效的 URL,您必须使用百分比转义编码来转义双引号
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.