/**
* 字典转为json
*
* @param dcit 字典类型数据
*
* @return json字符串
*/
- (NSString *)dictToJson:(NSDictionary *)userInf
{
// isValidJSONObject判断对象是否可以构建json对象
if (![NSJSONSerialization isValidJSONObject:userInf]) {
return nil;
}
NSError *error;
// 创造一个json从Data, NSJSONWritingPrettyPrinted指定的JSON数据产的空白,使输出更具可读性。
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userInf options:NSJSONWritingPrettyPrinted error:&error];
NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
return json;
}
/**
* json字符串转为字典
*
* @param json json字符串
*
* @return 字典类型数据
*/
- (NSDictionary*) jsonToDcit:(NSString*)json
{
if (!json || json.length == 0) {
return nil;
}
NSError *error = nil;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:&error];
if (error) {
NSLog(@"jsonToDcit failed: %@", error.description);
}
return dict;
}
JSONObjectWithData:options:error:方法来进行数据转换,这里的options是一个枚举值
即:
typedef NS_OPTIONS(NSUInteger, NSJSONReadingOptions) {
NSJSONReadingMutableContainers = (1UL << 0),
NSJSONReadingMutableLeaves = (1UL << 1),
NSJSONReadingAllowFragments = (1UL << 2)
} NS_ENUM_AVAILABLE(10_7, 5_0)
NSJSONReadingMutableContainers:返回可变容器,NSMutableDictionary或NSMutableArray。NSJSONReadingMutableLeaves:返回的JSON对象中字符串的值为NSMutableString
NSJSONReadingAllowFragments:允许JSON字符串最外层既不是NSArray也不是NSDictionary,
但必须是有效的JSON Fragment。例如使用这个选项可以解析 @“123” 这样的字符串,例如:
NSString *num=@"32";
NSError *error;
NSData *createdData = [num dataUsingEncoding:NSUTF8StringEncoding];
id response=[NSJSONSerialization JSONObjectWithData:createdData options:NSJSONReadingAllowFragments error:&error];
NSLog(@"Response= %@",response);
/**
* json data 转为字典
*
* @param json json data
*
* @return 字典类型数据
*/
- (NSDictionary*) jsonDataToDcit:(NSData *)data
{
if (!data) {
return nil;
}
NSError *error = nil;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
if (error) {
NSLog(@"jsonDataToDcit failed: %@", error.description);
}
return dict;
}