作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有 parsed
JSON
来自 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.name
和
arrayData.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/
我是一名优秀的程序员,十分优秀!