gpt4 book ai didi

json - RxSwift 解析 JSON 数组

转载 作者:行者123 更新时间:2023-11-30 12:27:39 25 4
gpt4 key购买 nike

我正在尝试从 JSON 响应创建一个字典数组。

这是代码

_ = postView.textView.rx.text
.subscribe(onNext: {[unowned self] _ in
let client = Alamofire.SessionManager.default
_ = client.request(Router.getFriends())
.rx_responseJSON()
.subscribe(onNext: { [weak self] data in
var names = [String]()
do {
let json = try JSONSerialization.jsonObject(with: data) as? [String: Any], //'var' declarations with multiple variables cannot have explicit getters/setters
let friends = json["user"] as? [[String: Any]] {
for friend in friends {
if let name = friend["first_name"] as? String {
names.append(name)
}
}
}
} catch {
print("Error deserializing JSON: \(error)")
}

print(names)
}, onError: { (error) -> Void in
debugPrint("Error: \(error)")
})

})

这是我遇到的错误

'var' declarations with multiple variables cannot have explicit getters/setters

这是JSON 响应

{
"user": [
{
"id": 2,
"first_name": "Knysys",
"photo": "https://graph.facebook.com/437334666655912/picture/?type=large",
"last_seen_event": null,
"blocked": false
},
{
"id": 3,
"first_name": "ATester",
"photo": "https://graph.facebook.com/379988632393252/picture/?type=large",
"last_seen_event": 7,
"blocked": false
}
]
}

所需的输出是这样的,,

var friends = [
[
"firstName": "SmartApps",
"photo": "https://graph.facebook.com/1248984075179327/picture/?type=large"
],

[
"firstName": "Knysys",
"photo": "https://graph.facebook.com/437334666655912/picture/?type=large"
],
[
"firstName": "ATester",
"photo": "https://graph.facebook.com/379988632393252/picture/?type=large"
]
]

提前致谢!

最佳答案

您忘记了 let json = ... 行中的 if

do {
if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
let friends = json["user"] as? [[String: Any]] {
for friend in friends {
if let name = friend["first_name"] as? String {
names.append(name)
}
}
}
} catch {
print("Error deserializing JSON: \(error)")
}

关于json - RxSwift 解析 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43976426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com