MJB MJB - 1 year ago 91
JSON Question

RxSwift parse JSON array

I'm trying to create an array of dictionaries from JSON response.

Here is the code.

_ = 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)")
})

})


This is the error I'm getting


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


This is the JSON response,

{
"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
}
]
}


The desired output is this,,

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"
]
]


Thanks in advance!

MJB MJB
Answer Source

Here is the code that worked,

let client = Alamofire.SessionManager.default
_ = client.request(Router.getFriends())
    .rx_responseJSON()
    .subscribe(onNext: { [weak self] data in
        self?.friends.removeAll()
        let json = data as? [String: Any]
        let friends = json?["user"] as! [[String: Any]]

        for i in 0 ..< friends.count{
            let firstName: String = (friends[i]["first_name"] as! NSString) as String
            let photo: String = (friends[i]["photo"] as! NSString) as String
            let dict = [
                "firstName" : firstName,
                "photo" : photo
            ]
            self?.friends.append(dict)
        }
        self?.friendTableView.reloadData()
        self?.friendTableView.sizeToFit()
        }, onError: { (error) -> Void in
           debugPrint("Error retrieving friends: \(error)")
    })
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download