开发中常用到JSON与字典数组的相互转换,这里做个笔记.
一:NSDictonary转JSON
+ (NSString *)jsonFromDic:(NSDictionary *)dic {
NSError *phraseErr = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&phraseErr];
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
二:数组转JSON
+ (NSString *)jsonFromArr:(NSString *)array {
NSError *err = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&err];
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
三:JSON转字典
- (NSDictionary *)dicFromJsonStr:(NSString *)jsonstr {
if (jsonstr == nil) {
return nil;
}
NSData *jsonData = [jsonstr dataUsingEncoding:NSUTF8StringEncoding];
NSError *pharseErr = nil;
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&pharseErr];
if (pharseErr) {
NSLog(@"解析失败%@",pharseErr);
return nil;
}
return dic;
}
网友评论