[英]Swift Codable Protocol. String encoding issue
最近我在對符合 Codable 協議的實體進行編碼時遇到了一個問題。
這是游樂場的代碼:
class Person: Codable {
var name: String?
var age: Int?
var isDev: Bool?
}
let p1 = Person()
p1.name = "John N."
p1.age = 13
p1.isDev = false
let p2 = Person()
p2.name = "Jack"
p2.age = 19
p2.isDev = true
let people = [p1, p2]
let data = try JSONEncoder().encode(people)
let j = try! JSONSerialization.jsonObject(with: data, options: [])
print(j)
這是我在 Playground 控制台中得到的 output:
如您所見,編碼的 p1 名稱帶有引號,但 p2 沒有。 所以我的問題是為什么?
PS 我注意到的唯一一件事是,在設置字符串值時在任意位置添加空格符號或下划線會在 json 中添加引號。 p1.name 包含一個空格,因此它被正確編碼。
任何想法表示贊賞。
j
是反序列化的 JSON object,而不是 JSON 字符串(編碼數據)。 如果要查看 JSON,請將data
轉換為字符串,即JSON:
print(String(data: data, encoding: .utf8)!)
j
實際上是使用NSArray
和NSDictionary
的 JSON 數據的表示。 事實證明,如果您打印帶有字符串的NSDictionary
,引號將添加到包含空格和/或其他特殊字符的字符串中,以告訴您字符串實際開始和結束的位置。
相比:
print(["name": "hello"] as NSDictionary)
print(["name": "hello world"] as NSDictionary)
print(["hello"] as NSArray)
print(["hello world"] as NSArray)
Output:
{
name = hello;
}
{
name = "hello world";
}
(
hello
)
(
"hello world"
)
這個答案不會解決實際問題,但我認為這是作者想要實現的問題。 在發布的代碼片段中,您實際上是在打印字典,而不是 JSON 字符串。 你正在做以下事情:
Person
object 轉換為 JSON 數據Dictionary
回想一下,JSON 數據實際上是 JSON 字符串的字節表示。
您可以通過執行以下操作檢查 JSON 字符串:
class Person: Codable {
var name: String?
var age: Int?
var isDev: Bool?
}
let p1 = Person()
p1.name = "John N."
p1.age = 13
p1.isDev = false
let p2 = Person()
p2.name = "Jack"
p2.age = 19
p2.isDev = true
let people = [p1, p2]
let data = try JSONEncoder().encode(people)
let jsonString = String(data: data, encoding: .utf8)
print(jsonString ?? "invalid JSON data")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.