- (void)dicToDataTodic{
NSDictionary *dic = @{@"name":@"tang",@"age":@"18"};
NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"NSDictionary 转 NSData = %@",data);
NSLog(@"NSData 转 NSDictionary =%@,%@",dictionary,dictionary[@"name"]);
NSDictionary *dic = @{@"name":@"tang",@"age":@"18"};
NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"NSDictionary 转 NSData = %@",data);
NSLog(@"NSData 转 NSDictionary =%@,%@",dictionary,dictionary[@"name"]);
}
------》以上就可以用
- dic转nsdata
+ (NSData *)returnDataWithDic:(NSDictionary *)dicP{
// 给所有的Key排序
NSArray *keys = [[dicP allKeys] sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [(NSString *)obj1 compare:obj2];
}];
NSMutableString *parame = [NSMutableString string];
//将字符串转NSData
for(NSUInteger i=0; i<[keys count]; i++) {
NSString *key = [keys objectAtIndex:i];
[parame appendFormat:@"%@=%@&",key,[dicP objectForKey:key]];
}
NSData * contentData = [parame dataUsingEncoding:NSUTF8StringEncoding];
return contentData;
}