JSON JavaScript Object Notation,轻量级数据交换格式。
一、文档结构
- 特点:无序的,“名称-值”对集合。
- 格式:对象{"名称1":"值1:","名称2":"值2",.....}
数组有序集合["值1","值1",......]
二、数据编码/解码
- SBJson 比较老的框架,更新频繁,支持ARC
- TouchJSON 比较老,支持ARC和MRC
- YAJL 比较优秀的JSON框架,基于SBJson优化,但不支持ARC
- **NextiveJson 非常优秀的JSON框架,与JSONKit性能相似,不支持ARC
- NSJSONSerialization iOS 5之后苹果提供的API,很优秀且快速,占用内存小,支持ARC,推荐使用
三、应用
3.1 NSJSONSerialization解码
NSError *jsonError;
NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError];
if (!jsonError || jsonError){
NSLog(@"解析失败!");
}else{
NSLog(@"解析成功!");
}
3.1 NSJSONSerialization编码
- (void)registerWithInfoDic:(NSDictionary *)infoDic complet:(void (^)(NSDictionary *netObject, BOOL isSeccuss))complete{
NSString *parameterStr = [[NSString alloc] initWithFormat:@"?localIp=%@&localPort=%@&userId=%@&userPwd=%@", [infoDic objectForKey:@"localIp"]
, [infoDic objectForKey:@"localPort"]
, [infoDic objectForKey:@"userId"]
, [infoDic objectForKey:@"userPwd"]
];
NSString *strUrl = [NSString stringWithFormat:@"http://192.168.0.45:8080/webDemo/Register%@",parameterStr];
strUrl = [strUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL *url = [NSURL URLWithString:strUrl];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *taskError){
NSLog(@"Register请求完成!");
if (!taskError) {
//NSError *jsonError = nil;
NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
complete(dataDic,YES);
}else{
NSLog(@"\ntask error: %@", taskError.localizedDescription);
complete(nil,NO);
}
}];
[task resume];
}
NSDictionary *dic = @{@"localIp":@"192.168.0.1",@"localPort":@"12345",@"userId":@"12345",@"userPwd":@"123456"};
//NSLog(@"测试按钮点击");
[[WebConnect sharedWebConnect] registerWithInfoDic:dic complet:^(NSDictionary *netObject, BOOL isSeccuss){
if (isSeccuss) {
NSLog(@"netObject: %@",netObject);
}
}];