我有一个返回 JSON 的 API,我想解析这个 JSON 并在我的应用程序中使用它。
我试过从这个获取方法:swift JSON login REST with post and get response example
代码:
func makeGetCall() {
// Set up the URL request
let todoEndpoint: String = "my link"
guard let url = URL(string: todoEndpoint) else {
print("Error: cannot create URL")
return
}
let urlRequest = URLRequest(url: url)
// set up the session
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
// make the request
let task = session.dataTask(with: urlRequest) {
(data, response, error) in
// check for any errors
guard error == nil else {
print("error calling GET on /public/api/services")
print(error!)
return
}
// make sure we got data
guard let responseData = data else {
print("Error: did not receive data")
return
}
// parse the result as JSON, since that's what the API provides
do {
guard let todo = try JSONSerialization.jsonObject(with: responseData, options: [])
as? [String: Any] else {
print("error trying to convert data to JSON")
return
}
// now we have the todo
// let's just print it to prove we can access it
print("The todo is: " + todo.description)
// the todo object is a dictionary
// so we just access the title using the "title" key
// so check for a title and print it if we have one
guard let todoTitle = todo["name"] as? String else {
print("Could not get todo title from JSON")
return
}
print("The title is: " + todoTitle)
} catch {
print("error trying to convert data to JSON")
return
}
}
task.resume()
}
我得到了一个输出:尝试将数据转换为 JSON 时出错。
我的 JSON 是:
[
{
"id": 1,
"name": "Services 1",
"description": "This is a description of Services 1. This is a description of Services 1 This is a description of Services 1. ",
"created_at": null,
"updated_at": null
},
{
"id": 2,
"name": "Services 2",
"description": "This is a description of Services 2. This is a description of Services 2 This is a description of Services 2. ",
"created_at": null,
"updated_at": null
}
]
为什么我在解析 JSON 时出错?
另外,如何循环数组并打印每一项?
例如:
service 1 description is: This is a description of Services 1. This is a description of Services 1 This is a description of Services 1.
service 2 description is: This is a description of Services 2. This is a description of Services 2 This is a description of Services 2.
最佳答案
请仔细阅读JSON。根对象显然是一个数组 ([]
)
guard let todos = try JSONSerialization.jsonObject(with: responseData) as? [[String: Any]] else {
print("error trying to convert data to JSON")
return
}
for todo in todos {
print(todo["name"] as? String ?? "n/a")
}
但是我建议使用Decodable
协议(protocol)。在类外声明这个结构
struct Service : Decodable {
let id : Int
let name, description : String
let createdAt : String?
let updatedAt : String?
}
并以这种方式解码 JSON
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let todos = try decoder.decode([Service].self, from: responseData)
for todo in todos {
print(todo.name)
}
} catch { print(error) }
旁注:
行 guard let responseData = data else {
永远不会到达 else
子句。如果 error
是 nil
——已经检查过了——那么可以保证 data
有一个值。
关于json - 快速解析 JSON 并在数组中循环时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49727329/