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对JSON数据进行编码/解码。首先,将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"}]">

最新更新