iOS Json和NSDictionary、NSArray 互转
2019-04-19 本文已影响0人
何以_aaa
与NSArray互转,下面方法只需将NSDictionary替换成NSArray
1.JSON to NSDictionary
- (NSDictionary *)dictionaryWithJson:(NSString *)jsonString {
if (jsonString == nil) {
return nil;
}
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *err;
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
if(err) {
NSLog(@"json解析失败:%@",err);
return nil;
}
return dic;
}
2.NSDictionary to JSON
- (NSString*)jsonWithDictionary:(NSDictionary *)dic
{
NSString *jsonString = nil;
if ([NSJSONSerialization isValidJSONObject:dic])
{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
jsonString =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
if (error) {
NSLog(@"Error:%@" , error);
}
}
return jsonString;
}