导入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
@H_301_243@NSArray
orNSDictionary
. -
All objects are instances of
@H_301_243@NSString
,NSNumber
,102)">NSArray,102)">NSDictionary,orNSNull
. -
All dictionary keys are instances of
@H_301_243@NSString
. -
Numbers are not NaN or infinity.
@H_301_243@
- 顶层对象必须是NSArray或者NSDictionary@H_301_243@
- 所有的对象必须是NSString、NSNumber、NSArray、NSDictionary、NSNull的实例@H_301_243@
- 所有NSDictionary的key必须是NSString类型@H_301_243@
- 数字对象不能是非数值或无穷@H_301_243@
- NSDictionary*registerDic=[NSDictionarydictionaryWithObjectsAndKeys:uuid,@"_id",userName,@"login_name",password,@"password",nil];@H_301_243@
- if([NSJSONSerializationisValidJSONObject:registerDic]){@H_301_243@
- NSError*error;@H_301_243@
- NSData*registerData=[NSJSONSerializationdataWithJSONObject:registerDic@H_301_243@
- options:NSJSONWritingPrettyPrintederror:&error];@H_301_243@
- NSLog(@"RegisterJSON:%@",[[NSStringalloc]initWithData:registerDataencoding:NSUTF8StringEncoding]);@H_301_243@
- }@H_301_243@
NSDictionary中的key就是json字符串中的key,object就是json字符串中的value,isValidJSONObject:方法是检测Foundation对象能否合法转换为JSON对象, dataWithJSONObject:options:error方法是将Foundation对象转换为JSON对象,参数 NSJSONWritingPrettyPrinted的意思是将生成的json数据格式化输出,这样可读性高,不设置则输出的json字符串就是一整行。
获取返回字符串中key为status的value: