我在Swift应用程序中序列化了一个JSON响应,解析后的结果是一个单字节数组
{
d = (
31,
139,
8,
0,
0,
9,
110,
136,
0,
255,
236,
125,
如何将此字节数组解码为可以使用的实际数据?
这是我的快速代码,用于获取和解析响应
`func getWRHPSData(completionHandlerForPOST:@escaping(_ result:AnyObject?,_ error:NSError?) - > Void) - >无效{
let request = NSMutableURLRequest(url: createURL())
request.httpMethod = "POST"
request.addValue("gzip, inflate", forHTTPHeaderField: "Accept")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let task = session.dataTask(with: request as URLRequest) { (data, response, error) in
func sendError(_ error: String) {
print(error)
let userInfo = [NSLocalizedDescriptionKey : error]
completionHandlerForPOST(nil, NSError(domain: "taskForGETMethod", code: 1, userInfo: userInfo))
}
/* GUARD: Was there an error? */
guard (error == nil) else {
sendError("There was an error with your request: \(error!)")
return
}
/* GUARD: Did we get a successful 2XX response? */
guard let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode >= 200 && statusCode <= 299 else {
sendError("Your request returned a status code other than 2xx!")
return
}
/* GUARD: Was there any data returned? */
guard let data = data else {
sendError("No data was returned by the request!")
return
}
/* 5/6. Parse the data and use the data (happens in completion handler) */
self.parseData(data, completionHandlerForConvertData: completionHandlerForPOST)
}
/* 7. Start the request */
task.resume()
}
// given raw JSON, return a usable Foundation object
private func parseData(_ data: Data, completionHandlerForConvertData: (_ result: AnyObject?, _ error: NSError?) -> Void) {
var parsedResult: AnyObject! = nil
do {
parsedResult = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as AnyObject
} catch {
let userInfo = [NSLocalizedDescriptionKey : "Could not parse the data as JSON: '\(data)'"]
completionHandlerForConvertData(nil, NSError(domain: "convertDataWithCompletionHandler", code: 1, userInfo: userInfo))
}
print(parsedResult)
completionHandlerForConvertData(parsedResult, nil)
}`