ios 字典or数组与json串互转
2017-02-24 本文已影响1300人
SunnyLeong
话不多说,直接上代码...
#pragma mark -字典转换成json串
- (NSString *)dictionaryToJsonString:(NSDictionary *)dict{
NSError *parseError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&parseError];
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
#pragma mark -数组转换成json串
- (NSString *)arrayToJsonString:(NSArray *)array{
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error];
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];;
}
#pragma mark -json串转换成字典
- (NSDictionary *)dictionaryWithJsonString:(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;
}
#pragma mark -json串转换成数组
- (id)arrayWithJsonString:(NSString *)jsonString{
if (jsonString == nil) {
return nil;
}
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *err;
NSArray *arr = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&err];
if(err) {
NSLog(@"json解析失败:%@",err);
return nil;
}
return arr;
}
// 将字典或者数组转化为JSON串
+ (NSData *)toJSONData:(id)theData
{
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:theData options:NSJSONWritingPrettyPrinted error:nil];
if ([jsonData length]&&error== nil){
return jsonData;
}else{
return nil;
}
}
// 将JSON串转化为字典或者数组
+ (id)toArrayOrNSDictionary:(NSData *)jsonData{
NSError *error = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
if (jsonObject != nil && error == nil){
return jsonObject;
}else{
// 解析错误
return nil;
}
}