我是JSON的新手,我正在尝试发帖子,我想知道如何检查我是否正确完成或检查它的返回值。这就是我所做的
NSURL *url = [NSURL URLWithString:@"http://json.myurl.com/.....];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
@"email", @"Email",
@"password", @"FirstName",
nil];
NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error];
[request setHTTPBody:postdata];
答案 0 :(得分:0)
检查JSON POST返回值:
NSString *strUrl=[NSString stringWithFormat:@"http://json.myurl.com/....."];
NSString *webStringURL = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:webStringURL];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
@"email", @"Email",
@"password", @"FirstName",
nil];
NSError* error;
NSData* postData = [NSJSONSerialization dataWithJSONObject:tmp options:NSJSONWritingPrettyPrinted error: &error];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *jsonData, NSError *error)
{
if (!error)
{
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:&error];
dispatch_async(dispatch_get_main_queue(),^
{
NSLog(@"jsonResponse--->%@",jsonResponse);
});
}
else
{
dispatch_async(dispatch_get_main_queue(),^
{
NSLog(@"error--->%@",error.description);
});
}
}];
要检查JSON格式是否正确,请查看此link
答案 1 :(得分:0)
对于初学者,我建议使用第三方框架,这种框架被世界各地的iOS开发人员广泛使用,称为AFNetworking
。
通过使用AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[manager POST:url parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
// TODO: Parse success here!
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
// TODO: Parse failure here!
}];
,HTTP请求非常简单:
responseObject
在给定的示例中,对象AFNetworking
是API响应JSON对象的表示。
{{1}}的安装和进一步使用说明可在website。
中找到