2

Swift 4 can't decode properly if json data contain new line ("\n"). What i can do for this case. Please take a look of my sample code :

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

If i change the userData value as like below that time it can decode properly.

var userData = """
[
     {
      "userId": 1,
     "id": 1,
     "title": "Title \\n with newline",
     "completed": false
     }
]
""".data(using: .utf8)

2 Answers2

3

This is invalid JSON. """ [ { "userId": 1, "id": 1, "title": "Title \n with newline", "completed": false } ] """

Please use following code

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)
}
Mitul.Patel
  • 252
  • 2
  • 8
2

This is invalid JSON:

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

Because this is written in swift, \n represents a new line in the whole JSON string. The above string literal represents this string:

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

Clearly, that is not valid JSON. If you do \\n, however, that represents a backslash and an n in Swift. Now the JSON is valid:

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

You don't need to worry about this, because whatever server is giving this data should give you valid JSON. You might have copied and pasted the response directly into a Swift string literal, forgetting to escape the backslash. This won't actually if you get the response programmatically.

Sweeper
  • 213,210
  • 22
  • 193
  • 313