如何使用以下格式在JSON数组中追加一个新值
https://next.json-generator.com/api/json/get/NJC7eX-oU
在上面的URL中如何追加数据字母数组?
{
"Letters": [
{
"Test1": [
{
"Priority": 1,
"Description": "A"
},
{
"Priority": 2,
"Description": "B"
}
],
"Test2": [
{
"Priority": 1,
"Description": "A"
}
]
}
]
}
你需要解码它
struct Root: Codable {
var letters: [[String:[Test]]]
enum CodingKeys: String, CodingKey {
case letters = "Letters"
}
}
struct Test: Codable {
let priority: Int
let description: String
enum CodingKeys: String, CodingKey {
case priority = "Priority"
case description = "Description"
}
}
do {
var res = try JSONDecoder().decode(Root.self, from:data)
res.letters.append(["test3":[Test(priority: 6, description: "des")]])
res.letters[0]["Test2"]?.append(Test(priority: 612, description: "des2"))
let wer = try JSONEncoder().encode(res)
let json = String(data: wer, encoding: .utf8)
print(json)
}
catch {
print(error)
}