Swift 5 - JSON具有嵌套 JSON 的编码器
Swift 5 - JSONEncoder with nested JSON
我正在尝试将 [[String : String]]
编码为具有 JSONEncoder()
的 JSON 嵌套对象。
Swift 输出示例:
[["firstName": "John", "lastName": "Doe"], ["firstName": "Tim", "lastName": "Cook"]]
编码后 JSON 的预期输出:
[
{
"firstName": "John",
"lastName": "Doe"
},
{
"firstName": "Tim",
"lastName": "Cook"
}
]
我将如何遍历这个字典数组然后用 JSONEncoder().encode()
对其进行编码?非常感谢!
JSONEncoder 默认给你 Data
。要将其恢复为 String
形式,您可以使用:
let input = [["firstName": "John", "lastName": "Doe"], ["firstName": "Tim", "lastName": "Cook"]]
do {
let json = try JSONEncoder().encode(input)
print(String(decoding: json, as: UTF8.self))
} catch {
print(error)
}
产生:
[{"firstName":"John","lastName":"Doe"},{"firstName":"Tim","lastName":"Cook"}]
使用Codable
到encode/decodeJSON数据。首先,将JSON转换成这样的对象,如果你更新更多字段会更容易:
struct Person: Codable {
var firstName: String
var lastName: String
}
假设你有一个Person
数组
var persons = [Person]()
persons.append(.init(firstName: "John", lastName: "Doe"))
persons.append(.init(firstName: "Tim", lastName: "Cook"))
//PRINT OUT
let jsonData = try! JSONEncoder().encode(persons)
let jsonString = String(data: jsonData, encoding: .utf8)
这是输出:
"[{"firstName":"John","lastName":"Doe"},{"firstName":"Tim","lastName":"Cook"}]"
我正在尝试将 [[String : String]]
编码为具有 JSONEncoder()
的 JSON 嵌套对象。
Swift 输出示例:
[["firstName": "John", "lastName": "Doe"], ["firstName": "Tim", "lastName": "Cook"]]
编码后 JSON 的预期输出:
[
{
"firstName": "John",
"lastName": "Doe"
},
{
"firstName": "Tim",
"lastName": "Cook"
}
]
我将如何遍历这个字典数组然后用 JSONEncoder().encode()
对其进行编码?非常感谢!
JSONEncoder 默认给你 Data
。要将其恢复为 String
形式,您可以使用:
let input = [["firstName": "John", "lastName": "Doe"], ["firstName": "Tim", "lastName": "Cook"]]
do {
let json = try JSONEncoder().encode(input)
print(String(decoding: json, as: UTF8.self))
} catch {
print(error)
}
产生:
[{"firstName":"John","lastName":"Doe"},{"firstName":"Tim","lastName":"Cook"}]
使用Codable
到encode/decodeJSON数据。首先,将JSON转换成这样的对象,如果你更新更多字段会更容易:
struct Person: Codable {
var firstName: String
var lastName: String
}
假设你有一个Person
数组
var persons = [Person]()
persons.append(.init(firstName: "John", lastName: "Doe"))
persons.append(.init(firstName: "Tim", lastName: "Cook"))
//PRINT OUT
let jsonData = try! JSONEncoder().encode(persons)
let jsonString = String(data: jsonData, encoding: .utf8)
这是输出:
"[{"firstName":"John","lastName":"Doe"},{"firstName":"Tim","lastName":"Cook"}]"