问题描述
我需要帮助才能在 ios swift 中读取 json。我知道我可以使用 decodeable 但这是我的 json 的一个例子。当我尝试 xith decodeable 时,我总是得到一个 nil 变量。
感谢您的帮助
[
{
"name": "Bob","age": "16","employed": "No"
},{
"name": "Vinny","age": "56","employed": "Yes"
}
]
这是我的代码,可解码
struct personResult: Decodable{
var person: [Person]
}
struct Person:Decodable{
var name: String
var age: String
var employed: String
}
这是我的功能
func getJson() {
let url = URL(string: myUrl)!
let task = URLSession.shared.dataTask(with: url,completionHandler: { (data,response,error) in
if let error = error {
print("Error : \(error)")
return
}
guard let httpResponse = response as? HTTPURLResponse,(200...299).contains(httpResponse.statusCode) else {
print("Error with the response,unexpected status code: \(response)")
return
}
if let data = data {
print(data)
do {
let result = try JSONDecoder().decode(personResult.self,from: data)
print(result)
}catch _ {
print("errror during json decoder")
}
}
})
task.resume()
}
}
我总是输入我的捕获,并打印错误消息
解决方法
你 JSON
是一个数组而不是字典,只是你的 Person
结构
struct Person:Decodable{
var name: String
var age: String
var employed: String
}
然后在函数中:
func getJson() {
let url = URL(string: myUrl)!
let task = URLSession.shared.dataTask(with: url,completionHandler: { (data,response,error) in
if let error = error {
print("Error : \(error)")
return
}
guard let httpResponse = response as? HTTPURLResponse,(200...299).contains(httpResponse.statusCode) else {
print("Error with the response,unexpected status code: \(response)")
return
}
if let data = data {
print(data)
do {
let result = try JSONDecoder().decode([Person].self,from: data)
print(result)
}catch let error {
print(error)
}
}
})
task.resume()
}
}