Swift 4罐';如果json数据包含新行(";\n";),则无法正确解码
如果json数据包含新行(“\n”),则Swift 4无法正确解码。我能为这个案子做些什么。请查看我的示例代码:Swift 4罐';如果json数据包含新行(";\n";),则无法正确解码,json,swift,decode,codable,Json,Swift,Decode,Codable,如果json数据包含新行(“\n”),则Swift 4无法正确解码。我能为这个案子做些什么。请查看我的示例代码: var userData = """ [ { "userId": 1, "id": 1, "title": "Title \n with newline", "completed": false } ] """.data(using: .utf8) struct User: Codable{ var userId: Int var id: Int var title:
var userData = """
[
{
"userId": 1,
"id": 1,
"title": "Title \n with newline",
"completed": false
}
]
""".data(using: .utf8)
struct User: Codable{
var userId: Int
var id: Int
var title: String
var completed: Bool
}
do {
//here dataResponse received from a network request
let decoder = JSONDecoder()
let model = try decoder.decode([User].self, from:userData!) //Decode JSON Response Data
print(model)
} catch let parsingError {
print("Error", parsingError)
}
如果我像下面那样更改userData值,那么它可以正确解码
var userData = """
[
{
"userId": 1,
"id": 1,
"title": "Title \\n with newline",
"completed": false
}
]
""".data(using: .utf8)
这是无效的JSON:
"""
[
{
"userId": 1,
"id": 1,
"title": "Title \n with newline",
"completed": false
}
]
"""
因为这是用swift编写的,\n
代表整个JSON字符串中的新行。上面的字符串文字表示此字符串:
[
{
"userId": 1,
"id": 1,
"title": "Title
with newline",
"completed": false
}
]
显然,这不是有效的JSON。但是,如果您使用了\\n
,则表示Swift中的反斜杠和n
。现在JSON是有效的:
[
{
"userId": 1,
"id": 1,
"title": "Title \n with newline",
"completed": false
}
]
您不必担心这一点,因为无论服务器提供什么数据,都应该提供有效的JSON。您可能已经将响应直接复制并粘贴到Swift字符串文字中,忘记了转义反斜杠。如果以编程方式获得响应,则实际上不会出现这种情况。这是无效的JSON。
"""
[
{
“用户ID”:1,
“id”:1,
“标题”:“标题\n带换行符”,
“已完成”:false
}
]
“”“
请使用以下代码
var userData : [[String:Any]] =
[
[
"userId": 1,
"id": 1,
"title": "Title \n with newline",
"completed": false
]
]
struct User: Codable{
var userId: Int
var id: Int
var title: String
var completed: Bool
}
do {
//here dataResponse received from a network request
let data = try? JSONSerialization.data(withJSONObject: userData, options:
[])
let decoder = JSONDecoder()
let model = try decoder.decode([User].self, from:data!) //Decode JSON
Response Data
print(model)
} catch let parsingError {
print("Error", parsingError)
}