字符串数据转字典、与反向转换

字典转字符串

- (NSString*)dictionaryToJson:(NSDictionary *)dic

{

NSError *parseError = nil;

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];

return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

}

字符串、NSData 转字典

- (id)jsonObject

{

if (!self)

{

return nil;

}

if ([self isKindOfClass:[NSData class]])

{

NSError *error = nil;

id object = [NSJSONSerialization JSONObjectWithData:(NSData*)self options:NSJSONReadingAllowFragments error:&error];

if (error)

{

DLog(@"--[%@]error--%@",NSStringFromSelector(_cmd),error);

}

return object;

}

if ([self isKindOfClass:[NSString class]])

{

NSData *data = [(NSString*)self dataUsingEncoding:NSUTF8StringEncoding];

NSError *error = nil;

id object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];

if (error)

{

DLog(@"--[%@]error--%@",NSStringFromSelector(_cmd),error);

}

return object;

}

return self;

}

你可能感兴趣的:(字符串数据转字典、与反向转换)