NSMutableData从Objective-C中的JSON响应中获取键值

时间:2019-05-12 11:57:31

标签: ios 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"}

任何帮助将不胜感激。

谢谢。

1 个答案:

答案 0 :(得分: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];

在您的情况下,它必须是NSArray *jsonArr而不是NSDictionary *jsonDict。然后,您只需检索特定键的值即可。

使用委托版本必须是这样的:

- (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);
}