导入JSONKIT和dylib
将json转换为NSDictionary
NSString *string =@"{\"name\": \"My Name\",\"list\": [\"one\",\"two\",\"three\"]}";
NSData* jsonData = [stringdataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *resultsDictionary = [jsonDataobjectFromJSONData];
NSLog(@"55----%@",resultsDictionary);
NSError *error = nil;
NSDictionary *dict_1 = [NSJSONSerializationJSONObjectWithData:request.responseDataoptions:kNilOptionserror:&error];
if (!dict_1 && error) {
NSLog(@"error-----------------------error");
return;
}else{
NSLog(@"OK-------------OK---------");
}
NSLog(@"dict_11111111------------------%@",dict_1);
NSString *str = [[NSStringalloc]initWithData:request.responseDataencoding:NSUTF8StringEncoding];
NSLog(@"str-----------------%@",str);
关于NSJSONSerialization,官方文档中有如下介绍:
You use theNSJSONSerialization
class to convert JSON to Foundation objects and convert Foundation objects to JSON.
An object that may be converted to JSON must have the following properties:
-
The top level object is an
NSArray
orNSDictionary
. -
All objects are instances of
NSString
,NSNumber
,102)">NSArray,102)">NSDictionary,orNSNull
. -
All dictionary keys are instances of
NSString
. -
Numbers are not NaN or infinity.
- 顶层对象必须是NSArray或者NSDictionary
- 所有的对象必须是NSString、NSNumber、NSArray、NSDictionary、NSNull的实例
- 所有NSDictionary的key必须是NSString类型
- 数字对象不能是非数值或无穷
- NSDictionary*registerDic=[NSDictionarydictionaryWithObjectsAndKeys:uuid,@"_id",userName,@"login_name",password,@"password",nil];
- if([NSJSONSerializationisValidJSONObject:registerDic]){
- NSError*error;
- NSData*registerData=[NSJSONSerializationdataWithJSONObject:registerDic
- options:NSJSONWritingPrettyPrintederror:&error];
- NSLog(@"RegisterJSON:%@",[[NSStringalloc]initWithData:registerDataencoding:NSUTF8StringEncoding]);
- }
NSDictionary中的key就是json字符串中的key,object就是json字符串中的value,isValidJSONObject:方法是检测Foundation对象能否合法转换为JSON对象, dataWithJSONObject:options:error方法是将Foundation对象转换为JSON对象,参数 NSJSONWritingPrettyPrinted的意思是将生成的json数据格式化输出,这样可读性高,不设置则输出的json字符串就是一整行。
- NSDictionary*resultJSON=[NSJSONSerializationJSONObjectWithData:resultData
- options:kNilOptionserror:&error];
获取返回字符串中key为status的value: