【iOS】打印NSDictionary为JSON格式

在网络请求的返回数据中,默认的NSLog打印的字典是这样的

2016-12-22 10:59:40.100 cnblogs[4766:834950] {
    message = "\U8be5\U7528\U6237\U4e0d\U5b58\U5728";
    success = 0;
}
  • 没有双引号
  • 不能打印中文
  • BOOL(true / false)值变成了0和1
  • 如果有数组,数组是以( )小括号的方式打印,而不是[ ]

这样的打印出的内容不能直接进行JSON格式化,解决方案是添加一个NSDictionary分类,将字典转为JSON打印

@implementation NSDictionary (MTHJSONOutput)

- (NSString *)descriptionWithLocale:(id)locale {
    NSString *output;
    @try {
        output = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
        output = [output stringByReplacingOccurrencesOfString:@"\\/" withString:@"/"]; // 处理\/转义字符
    } @catch (NSException *exception) {
        output = self.description;
    } @finally {
        
    }
    return  output;
}

@end

添加分类前


添加分类前

添加分类后


添加分类前

你可能感兴趣的:(【iOS】打印NSDictionary为JSON格式)