如何从RxSwift中的onNext获取正确的值?

问题描述 投票:1回答:1

我有来自parsedJSON URL数据,并且当填充subscriber时,array上的array会相应触发。但是我从onNext获得的数据看起来像这样:MyProject.People。如何获得实际值?这是我的代码:

guard let myURL = URL(string: "https://api.myjson.com/bins/e5gjk") else { return }
var myArray: Variable<[People]> = Variable([])

myArray.asObservable().subscribe(onNext: { arrayData in
    print("TRIGGERED", arrayData)

    }).disposed(by: bag)

Alamofire.request(myURL, method: .get)
    .validate()
    .responseJSON{ response in

    guard response.result.isSuccess else {
       print("Error")
       return
    }

    let json = JSON(response.result.value)

    for i in 0...json["employees"].count {
        let people = People()
        people.name = json["employees"][i]["firstName"].stringValue
         people.job = json["employees"][i]["job"].stringValue

         myArray.value.append(people)
    }

    for i in myArray.value {
        print(i.name)
        print(i.job)
    }
}

因此,arrayData返回MyProject.People,但应提供字符串。我已经尝试过arrayData.namearrayData.value.name,但没有显示任何内容。 People看起来像这样:

class People {
    var name = ""
    var job = ""
}
json swift alamofire rx-swift swifty-json
1个回答
0
投票

我会建议您使用Codable协议而不是JSON窗格。您可以在此处阅读有关Codable的更多信息:https://www.swiftbysundell.com/basics/codable/

可以这样简单:

class Employees: Codable {
    let employees: [Employee]
}

class Employee: Codable {
    let firstName: String
    let job: String
}

我也尝试简单的request,并且成功完成,我能够获得所有实体:(您可以将Alamofire响应从responseJSON更改为responseData

let employees = try! JSONDecoder().decode(Employees.self, from: response.data)
for employee in employees.employees {
    print("Name: \(employee.firstName), Job: \(employee.job)")
}
...
Name: Jocke, Job: developer
Name: Anna, Job: construction
Name: Peter, Job: pilot
© www.soinside.com 2019 - 2024. All rights reserved.