标签:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//[self takeRequestUrlWithString:@"http://127.0.0.1/test.json"];
//[self takeRequestUrlWithString:@"http://www.baidu.com"];
}
-(void)takeRequestUrlWithString:(NSString*)str
{
NSURL *url=[NSURL URLWithString:str];
NSURLRequest *request=[NSURLRequest requestWithURL:url cachePolicy:1 timeoutInterval:15];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if(!connectionError)
{
NSHTTPURLResponse *httpResponse=(NSHTTPURLResponse*)response;
if (httpResponse.statusCode==200) {
NSError *error=nil;
//返回的要么是字典要么是数组
id needData=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
if(error)
{
NSLog(@"JSON 解析出错:%@",error);
}
else{
NSLog(@"模型转换:数据为:%@",needData);
}
}
else
{
NSLog(@"服务器出错 ,错误码:%ld",httpResponse.statusCode);
}
}
else{
NSLog(@"连接错误!!!");
}
}];
}
@end
@interface RYDataModel : NSObject
@property(nonatomic,strong)NSNumber *age;
@property(nonatomic,copy)NSString*name;
@property(nonatomic,strong)NSDictionary*school;
+(instancetype)dataWithDict:(NSDictionary*)dict;
@end
@implementation RYDataModel
+(instancetype)dataWithDict:(NSDictionary*)dict
{
RYDataModel *model=[RYDataModel new];
[model setValuesForKeysWithDictionary:dict];
return model;
}
@end
标签:
原文地址:http://www.cnblogs.com/tangranyang/p/4718246.html