如何解决修改json对象数组
我有一个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: [])
}
但是accounts数组是不可变的。我尝试过强制转换为NSMutableDictionary和NSMutableArray,但似乎无法使其正常工作。有人有提示吗?
解决方法
您需要使用var
声明的变量,而不是通过索引访问accounts数组
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
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。