Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
528 views
in Technique[技术] by (71.8m points)

ios - Swift String escaping when serializing to JSON using Codable

I'm trying to serialize my object as following:

import Foundation

struct User: Codable {
    let username: String
    let profileURL: String
}

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

let json = try? JSONEncoder().encode(user)

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

However on macOS I'm getting the following:

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

(note escaped '/' character).

While on Linux machines I'm getting:

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

How can I make JSONEncoder return the unescaped?

I need the string in JSON to be strictly unescaped.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...