【问题标题】:Swift 4 can't decode properly if json data contain new line ("\n") [duplicate]如果 json 数据包含换行符(“\n”),则 Swift 4 无法正确解码 [重复]
【发布时间】:2019-05-07 19:12:10
【问题描述】:

如果 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)

【问题讨论】:

    标签: json swift decode codable


    【解决方案1】:

    这是无效的 JSON。 """ [ { “用户ID”:1, “身份证”:1, "title": "标题 \n 带换行符", “完成”:假 } ] """

    请使用以下代码

    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)
    }
    

    【讨论】:

      【解决方案2】:

      这是无效的 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 字符串文字中,而忘记转义反斜杠。如果您以编程方式获得响应,这实际上不会。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多