简体   繁体   中英

NSMutableData Get Key Value from JSON response in Objective-C

I'm making a request to an API and getting the result back into _responseData like this:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    _responseData = [[NSMutableData alloc] init];
}

The response is what I'm expecting, a JSON snippet (receipt) - however how do I parse this NSMutableData as JSON so that I can extract the application_version - the response looks like this (removed some content):

{
"receipt":{"receipt_type":"ProductionSandbox", "adam_id":0, "app_item_id":0, "application_version":"1.0", 
"in_app":[
{"quantity":"1"}

Any help would be appreciated.

Thanks.

Easiest way is using the version with a completion handler:

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];

Instead of NSArray *jsonArr it has to be NSDictionary *jsonDict in your case. Then you can simply retrieve the values for specific keys.

Using the delegate version it has to be something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM