手动解析
//json:也是一种数据解析格式,键值对形式
- (void)viewDidLoad {
[super viewDidLoad];
//xlm :sax(标签对解析) dom(属性解析)
//json:也是一种数据解析格式,键值对形式
//NSString * str = @"{\"key\":\"value\"}";
//字典{}:里面存的都是:键值对
//数组[]:里面存的是:值
//json解析类:NSJSONSerialization
//json解析之后是数组或者字典
NSURL* url = [NSURL URLWithString:@"http://localhost:8080/Login1/NewServlet?command=5"];
NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *_Nullableresponse,NSData *_Nullabledata,NSError *_NullableconnectionError) {
NSString * str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"data -----%@",str);
NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//接收请求到的数据
//-号方法
///BaseClass * base = [[BaseClass alloc] initWithData:dic];
//+号方法更为简洁方便
BaseClass * base = [BaseClassb aseClassWithDic:dic];
NSLog(@"base.userArr.count ===== %ld",base.userArr.count);
}];
}
BaseClass.m
//自定义对象类初始化方法
- (id)initWithDic:(NSDictionary*)dic {
if(self= [super init]) {
_userArr= [[NSMutableArray alloc] init];
//类中接收数据中名为"Parma"的数组
NSArray * arr = [dic objectForKey:@"parma"];
NSLog(@"arr ----- %@",arr);
//遍历数组的字典
for(NSDictionary * userDic in arr) {
//对象接收从数组中取出的字典
User * user = [[User alloc] initWithDic:userDic];
//在接收对象的数组里添加解析后的对象
[_userArr addObject:user];
}
}
return self;
}
+ (id)baseClassWithDic:(NSDictionary*)dic {
return[[self alloc] initWithDic:dic];
}
User.m
//自定义对象初始化方法
- (id)initWithDic:(NSDictionary*)dic {
if(self= [super init]) {
//对象对接收来的字典进行解析并接收值
self.name= [dicobjectForKey:@"name"];
self.pwd= [dicobjectForKey:@"pwd"];
self.age= [dicobjectForKey:@"age"];
self.trueName= [dicobjectForKey:@"tureName"];
}
return self;
}