我有来自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
协议而不是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