Swift String escaping when serializing to JSON using Codable

For iOS 13+ / macOS 10.15+

You can use .withoutEscapingSlashes option to json decoder to avoid escaping slashes

let user = User(username: "John", profileURL: "http://google.com")

let jsonEncoder = JSONEncoder()
jsonEncoder.outputFormatting = .withoutEscapingSlashes
let json = try? jsonEncoder.encode(user)

if let data = json, let str = String(data: data, encoding: .utf8) {
    print(str)
}

Console O/P

{“profileURL”:”http://google.com“,”username”:”John”}


NOTE: As mention by Martin R in comments \/ is a valid JSON escape sequence.

Leave a Comment