修改 json 个对象的数组
Modify an array of json objects
我有一个 json 对象列表,我需要修改每个对象中的值。我正在访问以下代码中的 json 个对象列表:
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
let objects = json["data"] as? [String: Any]
if let accounts = objects?["accounts"] as? [[String:Any]]{
print("Accounts: \(accounts)")
for account in accounts {
account["balance"] = nil
}
}
modifiedData = try JSONSerialization.data(withJSONObject: json, options: [])
}
但是帐户数组是不可变的。我试过投射到 NSMutableDictionary 和 NSMutableArray 但似乎无法让它工作。有人有什么建议吗?
您需要使用 var
声明的变量,并改为通过索引访问帐户数组
if var json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
var objects = json["data"] as? [String: Any]
if var accounts = objects?["accounts"] as? [[String:Any]] {
for index in 0..<accounts.count {
accounts[index]["balance"] = 0
}
objects?["accounts"] = accounts
}
json["data"] = objects
}
我有一个 json 对象列表,我需要修改每个对象中的值。我正在访问以下代码中的 json 个对象列表:
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
let objects = json["data"] as? [String: Any]
if let accounts = objects?["accounts"] as? [[String:Any]]{
print("Accounts: \(accounts)")
for account in accounts {
account["balance"] = nil
}
}
modifiedData = try JSONSerialization.data(withJSONObject: json, options: [])
}
但是帐户数组是不可变的。我试过投射到 NSMutableDictionary 和 NSMutableArray 但似乎无法让它工作。有人有什么建议吗?
您需要使用 var
声明的变量,并改为通过索引访问帐户数组
if var json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
var objects = json["data"] as? [String: Any]
if var accounts = objects?["accounts"] as? [[String:Any]] {
for index in 0..<accounts.count {
accounts[index]["balance"] = 0
}
objects?["accounts"] = accounts
}
json["data"] = objects
}