I have parsed
JSON
data from an URL
and the subscriber
on the array
trigger accordingly as the array
is populated. But the data that I get from onNext
look like this: MyProject.People
. How do I get the actual values? Here's my code:
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)
}
}
So, arrayData
returns MyProject.People
but should give strings. I have tried arrayData.name
and arrayData.value.name
but it doesn't show anything. People
look like this:
class People {
var name = ""
var job = ""
}
I would suggested you to use Codable
protocol instead of JSON
pod. You can read more about Codable
here: https://www.swiftbysundell.com/basics/codable/
And more about CustomStringConvertible
here: https://developer.apple.com/documentation/swift/customstringconvertible
This can be as simple as this:
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
}
I also try simple request
and it's finish successfully, i was able to get all entities: (you can change Alamofire response from responseJSON
to 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
myArray.value is an array of [People], it's not allowed direct access people property (name, job). You have to get people from particular index, then you can access people's property.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.