[英]JSON Data is nil after decoding
Guys I am getting a response for an api call I make.伙计们,我收到了我发出的 api 调用的响应。 it returns the whole response and I give it to the method like.它返回整个响应,我将它提供给类似的方法。
completionHandler(response: response, error: nil)
then by doing然后通过做
print(response.description)
The result is that I get headers statuscode etc.结果是我得到了标题状态码等。
URL:
removed
Status Code:
200
Headers:
Keep-Alive: timeout=5, max=99
Content-Length: 2423
Server: Apache/2.4.10 (Debian)
SessionID: removed
Content-Type: application/json
Date: Thu, 24 Sep 2015 12:50:14 GMT
Connection: Keep-Alive
Cache-Control: no-cache
Payload:
[{"id":148,"name":"Amsterdam","avatar":"removed","cover":"removed"}]
The part I am mostly interested in is this part我最感兴趣的部分是这部分
Payload:
[{"id":148,"name":"Amsterdam","avatar":"removed","cover":"removed"}]
Somehow I can't extract that array of json objects.不知何故,我无法提取该 json 对象数组。 Anyone who can help me out on how to get this?谁能帮我解决这个问题?
EDIT: added the method where I receive the response and pass it through编辑:添加了我接收响应并将其传递的方法
func requestObj(url: Routes, params: Dictionary<String, String>?, completionHandler: (response: Response?, error: NSError?) -> ())
{
self.requestConfig(completionHandler: { () -> () in
if let req = NSMutableURLRequest(urlString: self.config!.api!.baseUrl! + "/v2" + url.rawValue) {
do {
req.addValue(String(self.config!.api!.token!), forHTTPHeaderField: "Token")
req.addValue(String(self.sessionID), forHTTPHeaderField: "SessionID")
let opt = HTTP(req)
opt.start { response in
if let err = response.error {
print("error: \(err.localizedDescription)")
print("opt finished with error info: \(response.description)")
completionHandler(response: nil, error: nil)
}
completionHandler(response: response, error: nil)
//print("data is: \(response.data)") access the response of the data with response.data
}
}
}
}) // request a valid config before doing anything
}
This is called with这被称为
adapter.requestObj(APIAdapter.Routes.getMunicipalities, params: nil, completionHandler: {(
response, error) in
if let response = response {
print(response.description)
}
})
对于SwiftHTTP ,您可以通过以下方式获取响应正文:
response.data
Have you already tried with "SwiftyJson" you could save the data in a JSON object and then access the data as a Dictionary here's how I deal with the data您是否已经尝试过使用“SwiftyJson”,您可以将数据保存在 JSON 对象中,然后将数据作为字典访问,这是我处理数据的方式
import Alamofire
import SwiftyJSON
func RequestImages()
{
Alamofire.request(.GET, "https://api.500px.com/v1/photos",parameters:["consumer_key":"gRU4LletUCA9RiOQhaJBAt62UyRRYUE6vsIcC7fO"])
.responseJSON { _,_,result in
switch result {
case .Success(let data):
let json = JSON(data)
debugPrint(data)
self.Photos = self.ParseJSON(json)
self.performSegueWithIdentifier("ToCollection", sender: self)
case .Failure(_, let error):
print("Request failed with error: \(error)")
}
}
}
here is some code where I use a library called Alamofire where i retrieve a response in JSON, then if data has be found i save the data in a JSON object provided by the SwiftyJSON library这是我使用名为 Alamofire 的库的一些代码,我在其中检索 JSON 中的响应,然后如果找到数据,我将数据保存在 SwiftyJSON 库提供的 JSON 对象中
let json = JSON(data)
then I have a collection of an "Image" mode called "Photos" i fill this collection by parsing the JSON data as the following然后我有一个名为“照片”的“图像”模式的集合,我通过解析 JSON 数据来填充这个集合,如下所示
func ParseJSON(json:JSON)->[Image]
{
//Get Image_URL
var pictures = [Image]()
for result in json["photos"].arrayValue
{
pictures.append(Image(url: result["image_url"].stringValue, name: result["name"].stringValue, news: result["description"].stringValue))
}
debugPrint(pictures)
return pictures
}
I hope my implementation helps you Greetings!我希望我的实现可以帮助你问候!
Try this :-尝试这个 :-
override func viewDidLoad() {
super.viewDidLoad()
get_data_from_url("http://yourURL")
}
func get_data_from_url(url:String) {
let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
Id = label1.text //your request parameters
JId = label2.text //your request parameters
var post:NSString = "uid=\(Id)&jid=\(JId)"
//NSLog("PostData: %@",post);
var url:NSURL = NSURL(string: url)!
var postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
var postLength:NSString = String( postData.length )
var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = postData
request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("*/*", forHTTPHeaderField: "Accept")
var reponseError: NSError?
var response: NSURLResponse?
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)
if urlData != nil && reponseError == nil {
let res = response as! NSHTTPURLResponse!;
//NSLog("Response code: %ld", res.statusCode);
if (res.statusCode >= 200 && res.statusCode < 300) {
var responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
NSLog("Response ==> %@", responseData)
if Id != nil {
extract_json(urlData!)
}
} else {
var alertView:UIAlertView = UIAlertView()
alertView.title = "Sign in Failed!"
alertView.message = "Connection Failed"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
} else {
var alertView:UIAlertView = UIAlertView()
alertView.title = "Sign in Failed!"
alertView.message = "Connection Failure"
if let error = reponseError {
alertView.message = (error.localizedDescription)
}
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
}
func extract_json(data:NSData) {
var error: NSError?
let jsonData:NSArray = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as! NSArray
let Id_temp: AnyObject? = ((jsonData)[0] as! NSDictionary)["id"]
let Name_temp: AnyObject? = ((jsonData)[0] as! NSDictionary)["name"]
}
First go to this site and validate your URL首先访问此站点并验证您的 URL
https://chrome.google.com/webstore/detail/advanced-rest-client/hgmloofddffdnphfgcellkdfbfbjeloo?utm_source=chrome-app-launcher-info-dialog ( GOOGLE extenstion ) then replace below given values according to your settings :- https://chrome.google.com/webstore/detail/advanced-rest-client/hgmloofddffdnphfgcellkdfbfbjeloo?utm_source=chrome-app-launcher-info-dialog(GOOGLE扩展)然后根据您的设置替换以下给定值:-
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("*/*", forHTTPHeaderField: "Accept")
Try with this:试试这个:
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:response options:0 error:&error];
Then you can do [jsonDictionary objectForKey:@""]
to retrieve values.然后你可以做[jsonDictionary objectForKey:@""]
来检索值。
This is Objective C, but I am sure it must be similar in Swift.这是 Objective C,但我相信它在 Swift 中一定是相似的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.