一:返回二进制数据
// 需要序列化
//使用系统自带的JSONSerialization进行foundation对象和json的互转
- (void)testjson {
//字典数组对象转json:顶层对象必须是NSArray或NSDictionary;判断是否合法对象isValidJSONObject
NSDictionary *dict = @{@"key1":@40,@"key2":@"value2",@"key3":@"value3"};
BOOL flag = [NSJSONSerialization isValidJSONObject:dict];
if (flag) {
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"%@",jsonString);
}
//json转字典,error可判断是否转化成功
NSString *json = @"{\n \"key1\" : 40,\n \"key3\" : \"value3\",\n \"key2\" : \"value2\"\n}";
NSError *error = nil;
NSData *data = [json dataUsingEncoding:NSUTF8StringEncoding];
//NSJSONReadingMutableContainers:表示将data数据转为可变的数组或字典,如果data数据既不是数组也不是字典,或者说格式错误,那么返回nil并抛出错误。
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
if (error) {
NSLog(@"error");
} else {
NSLog(@"%@",responseDict);
}
}
————————————
二:返回json格式数,AFN直接返回即可,AFNetworking已经帮我们序列化好了,我们可以直接使用。
三:网络请求注意事项如下
/*
1:iOS 7以后用这个
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
2:设置请求格式,默认-AFHTTPRequestSerializer
AFHTTPRequestSerializer:第一种是普通的http的编码格式也就是mid=10&method=userInfo&dateInt=20160818,这种格式的。
AFJSONRequestSerializer:第二种也是json编码格式的,也就是编码成{“mid”:“11”,“method”:“userInfo”,“dateInt”:“20160818”}
3:设置返回解析格式-默认–AFJSONResponseSerializer
我们使用AFNetworking时常用的解析器是AFJSONResponseSerializer,这样可以在block中直接得到字典或数组对象,因为AFNetworking已经帮我们序列化好了,我们可以直接使用。
*/
参考:
https://www.jianshu.com/p/609351473b04