gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:18:57 25 4
gpt4 key购买 nike

我有 parsed JSON来自 URL 的数据和 subscriberarray相应地触发为 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 = ""
}

最佳答案

我会建议 您使用 Codable协议(protocol)而不是 JSON荚。
您可以阅读更多关于 Codable 的信息这里:https://www.swiftbysundell.com/basics/codable/

更多关于 CustomStringConvertible这里:
https://developer.apple.com/documentation/swift/customstringconvertible

这可以像这样简单:

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

/// If you want to print array with values
/// A textual representation of this instance.
extension Employees: CustomStringConvertible {
var description: String {
var text = ""
for employee in employees {
text += "Employee first name: \(employee.firstName), Job: \(employee.job)\n"
}
return text
}
}

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

我也尝试简单的 request它成功完成,我能够获得所有实体:(您可以将 Alamofire 响应从 responseJSON 更改为 responseData )
let employees = try! JSONDecoder().decode(Employees.self, from: response.data)
print(employees)
...
Employee first name: Jocke, Job: developer
Employee first name: Anna, Job: construction
Employee first name: Peter, Job: pilot

关于json - 如何从 RxSwift 中的 onNext 获取正确的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59423384/

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