iOS 数组/字典与字符串互相转换

JSON字符串转Dictionary

+ (NSDictionary *)getDictionaryWithJsonString:(NSString *)jsonString{

NSData *jsonData = [jsonString dataUsingEncoding:NSASCIIStringEncoding];

NSError *error = nil;

id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData

options:NSJSONReadingAllowFragments

error:&error];

if (jsonObject != nil && error == nil){

return jsonObject;

}else{

// 解析错误

return nil;

}

}


JSON字符串转Array

+ (NSArray *)getArrayWithJsonString:(NSString *)jsonString{

NSData *jsonData = [jsonString dataUsingEncoding:NSASCIIStringEncoding];

NSError *error = nil;

id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData

options:NSJSONReadingAllowFragments

error:&error];

if (jsonObject != nil && error == nil){

return jsonObject;

}else{

// 解析错误

return nil;

}

}


Array转JSON字符串

+ (NSString *)getJsonStringWithArray:(NSArray *)array{

if (array.count > 0) {

NSData *data = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:nil];

NSString *jsonStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

jsonStr = [jsonStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; //去除掉首尾的空白字符和换行字符

jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\r" withString:@""];

jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];

return jsonStr;

}

return @"";

}



Dictionary转JSON字符串

+ (NSString *)getJsonStringWithDictionary:(NSDictionary *)dictionary{

NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:nil];

NSString *jsonStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

jsonStr = [jsonStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; //去除掉首尾的空白字符和换行字符

jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\r" withString:@""];

jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];

return jsonStr;

return @"";

}

你可能感兴趣的:(iOS 数组/字典与字符串互相转换)