NSData *weatherData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:@"our URL"]];
NSMutableDictionary *weatherDict = [NSJSONSerialization JSONObjectWithData:weatherData options:kNilOptions error:&error];
使用NSDATA对JSON数据进行Getiing是否正确?
答案 0 :(得分:1)
For parser JSON better options use:
1) NSURLSession.
2) AFNetworking .
Using above approve you can handle response and error (If the request failed or encountered an error )
For NSURLSession :
-(void)getJsonResponseFromServer : (NSString *)urlString parameter :(NSDictionary*)parameter success : (void (^)(NSDictionary *responseDict))success failure:(void(^)(NSError* error))failure
{
NSError* error=nil;
NSURLSession * session = [NSURLSession sharedSession];
NSURL * url = [NSURL URLWithString: urlString];
NSData *postData = [NSJSONSerialization dataWithJSONObject:parameter options:0 error:&error];
//Create URLReques
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
// [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
// Set Method POST/GET
[request setHTTPMethod:@"POST"];
//set Parameter
[request setHTTPBody:postData];
// Asynchronously Api is hit here
NSURLSessionDataTask* dataTask=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (!error) //If error nil
{
//Serialization data
NSDictionary * json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"json %@",json);
success(json);
}
else
{
failure(error);
}
}];
[dataTask resume] ; // Executed task
}
只需致电:
NSDictionary* paramDict=@{@“paramterName”:@“value”};
[self getJsonResponseFromServer:@BaseURL parameter:paramDict success:^(NSDictionary *responseDict)
{
NSLog(@"responce %@",responseDict);
} failure:^(NSError *error)
{
// error handling here ...
NSLog(@"error %@",error.description);
}];
为了更好地理解NSURLSession Class Reference,请参阅: