[英]NSMutableData Get Key Value from JSON response in Objective-C
我正在向API发出请求,并将结果返回到_responseData
如下所示:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
_responseData = [[NSMutableData alloc] init];
}
响应是我所期望的,是一个JSON代码段(接收)-但是,我如何将NSMutableData
解析为JSON,以便我可以提取application_version
响应看起来像这样(删除了一些内容):
{
"receipt":{"receipt_type":"ProductionSandbox", "adam_id":0, "app_item_id":0, "application_version":"1.0",
"in_app":[
{"quantity":"1"}
任何帮助,将不胜感激。
谢谢。
最简单的方法是使用带有完成处理程序的版本:
NSURL *url = [NSURL URLWithString:@"https://jsonplaceholder.typicode.com/users"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
request.HTTPBody = [@"foo=bar" dataUsingEncoding:NSUTF8StringEncoding];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSArray *jsonArr = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"%@", jsonArr);
}];
[task resume];
在您的情况下,必须使用NSDictionary *jsonDict
而不是NSArray *jsonArr
。 然后,您可以简单地检索特定键的值。
使用委托版本必须是这样的:
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
self.data = [NSMutableData data];
completionHandler(NSURLSessionResponseAllow);
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
[self.data appendData:data];
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
NSArray *jsonArr = [NSJSONSerialization JSONObjectWithData:self.data options:0 error:nil];
NSLog(@"%@", jsonArr);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.