Swift JSONDecoder loses special character from string

Viewed 75

I have a JSON object, which has the key value: "content":""

Actually, the value of content is 7 BOM characters, you can copy it into SublimeText to view it. But when I use the command in the Swift:

let object = try JSONDecoder().decode(type, from: data)

then object.content only has 6 characters.

Do you know why and how to fix it?

This full example shows the issue:

import Foundation

let bom: Character = "\u{FEFF}"
let string = String(repeating: bom, count: 7)
print(string.count) // 7

let json = #"{"content": "\#(string)" }"#.data(using: .utf8)!

struct Type: Decodable {
    let content: String
}

let decoded = try! JSONDecoder().decode(Type.self, from: json)
print(decoded.content.count) // 6

One of the special characters is lost during JSON parsing.

0 Answers
Related