[英]Parsing multiple arrays from a JSON object in Swift
I am building an iOS app
using Swift3
and for part of the app, I send an HTTP POST
request to a webpage which returns a JSON
object containing 5 different arrays. 我正在使用
Swift3
构建iOS app
,对于应用的一部分,我向网页发送了HTTP POST
请求,该请求返回包含5个不同数组的JSON
对象。 I wish to receive this JSON object in Swift
and have these arrays in a readable format (NSArray). 我希望
JSON object in Swift
接收此JSON object in Swift
并以可读格式(NSArray)拥有这些数组。 Below is exactly what my webpage returns. 以下正是我的网页返回的内容。
{"className":["U.S. History 2 (AP)","Chemistry (HN)","Algebra 2 (HN)","Spanish 3 (HN)"],"teacherLastName":["Schartner","Racz","Johnson","Burdette"],"teacherFirstName":["Lindsey","Gregory","Shane","Joy"],"teacherTitle":["Mrs.","Mr.","Mr.","Sra."],"classID":["0001","0002","0003","0004"]}
I am attempting to do the following in my Swift code. 我正在尝试在我的Swift代码中执行以下操作。 I am not entirely sure where to go from here, but this is what I have so far.
我不确定从这里要去哪里,但这是我到目前为止所要做的。
func getClassList() -> NSArray{
let myUrl = URL(string: "http://papili.us/studycentral/api/getClassList.php");
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"// Compose a query string
let postString = "";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil {
print("error=\(error)")
return
}
// Print out response object
print("response = \(response)")
//Convert response sent from a server side script to a NSDictionary object:
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
// Access value of username, name, and email by its key
let newdata : NSDictionary = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
let info : NSArray = newdata.value(forKey: "className") as! NSArray
self.classList = info
}
} catch {
print(error)
}
}
task.resume()
return self.classList
}
Can someone explain what I need to do in order to properly read the arrays in my JSON object? 有人可以解释我需要做些什么才能正确读取JSON对象中的数组吗? Thank you very much
非常感谢你
Kyle, 凯尔,
There are a number of things going on here. 这里发生了很多事情。 The biggest mistake you are making is treating an asynchronous function as a synchronous one.
您犯的最大错误是将异步函数视为同步函数。 The closure that you pass to
dataTask
gets executed asynchronously meaning it will not have completed (most likely) by the time you return self.classList
. 传递给
dataTask
的闭包dataTask
异步方式执行,这意味着到return self.classList
时,闭包将尚未完成(很可能)。 To rectify that problem, your getClassList
method should itself take a closure that it will call when the data task completes. 为了解决该问题,您的
getClassList
方法本身应该采取封闭措施,该任务将在数据任务完成时调用。
It would look something like this: 它看起来像这样:
func getClassList(completion: ((NSArray?, NSError?) -> Void)?) {
let myUrl = URL(string: "http://papili.us/studycentral/api/getClassList.php");
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"// Compose a query string
let postString = "";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil {
print("error=\(error)")
completion?(nil, error)
return
}
// Print out response object
print("response = \(response)")
//Convert response sent from a server side script to a NSDictionary object:
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
// Access value of username, name, and email by its key
let newdata : NSDictionary = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
let info : NSArray = newdata.value(forKey: "className") as! NSArray
completion?(info, nil)
}
} catch {
print(error)
completion?(nil, error)
}
}
task.resume()
}
The way you would access this data is by calling getClassList
with a closure that takes an NSArray?
访问此数据的方式是通过调用带有带有
NSArray?
的闭包的getClassList
NSArray?
and NSError?
和
NSError?
and does what you want with them. 并与他们一起做你想要的。 This is similar to how you called
dataTask
. 这类似于您调用
dataTask
。
Also, this request looks more likely to be a GET
than a POST
to me. 另外,对我来说,此请求看起来更像是
GET
不是POST
。 Double check that you are constructing your request according to the API you are using. 仔细检查您是否根据所使用的API构建请求。
There are a number of other ways I'd suggest cleaning this code up, but I think these are the main points to move you forward. 我建议您采用多种其他方式来清理此代码,但我认为这些是使您前进的主要要点。
Check this Library: JSONParserSwift 检查此库: JSONParserSwift
You can parse your JSON easily. 您可以轻松解析JSON。
Just create following model: 只需创建以下模型:
class BaseModel: ParsableModel {
var className: [String]?
var teacherLastName: [String]?
var teacherFirstName: [String]?
var teacherTitle: [String]?
var classID: [String]?
}
Now call following method: 现在调用以下方法:
do {
let parsedModel: BaseModel = try JSONParserSwift.parse(string: jsonString)
} catch {
print(error)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.