记录最近用到的NSData转NSString、NSDictionary方法,方便以后查阅
// NSData转NSString
NSString *resultStr = [[NSString alloc] initWithBytes:[data bytes]
length:data.length
encoding:NSUTF8StringEncoding];
// NSData转NSDictionary
NSError *error;
NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&error];
// NSDictionary转NSData
// isValidJSONObject:判断一个对象能否转换成JSON对象
if ([NSJSONSerialization isValidJSONObject:dictionary]) {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary
options:NSJSONWritingPrettyPrinted
error:&error];
}
// NSDictionary转成json字符串
/**
*NSJSONWritingPrettyPrinted的意思是将生成的json数据格式化输出,
*这样可读性高,不设置则输出的json字符串就是一整行。
*/
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary
options:NSJSONWritingPrettyPrinted
error:&error];
NSString *jsonString;
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];