如果json数据包含换行符(“ \ n”),Swift 4将无法正确解码

时间:2018-12-06 06:00:56

标签: 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: 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)

2 个答案:

答案 0 :(得分:2)

这是无效的JSON。     “”     [       {         “ userId”:1         “ id”:1         “ title”:“标题\ 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)
}

答案 1 :(得分:0)

这是无效的JSON:

"""
[
 {
  "userId": 1,
 "id": 1,
 "title": "Title \n with newline",
 "completed": false
 }
]
"""

因为这是快速编写的,所以\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字符串文字中,却忘记了避免使用反斜杠。如果您以编程方式获得响应,则实际上不会。