RxSwift解析JSON数组

时间:2017-05-15 09:54:06

标签: json swift alamofire rx-swift

我正在尝试从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'声明不能显式   getter / setter方法

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

提前致谢!

2 个答案:

答案 0 :(得分:0)

您忘记了行if

中的let json = ...
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)")
}

答案 1 :(得分:0)

这是有效的代码,

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