【iOS】打印NSDictionary为JSON格式

作者: lancely | 来源:发表于2016-12-22 11:07 被阅读381次

在网络请求的返回数据中,默认的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

添加分类前


添加分类前

添加分类后


添加分类前

相关文章

网友评论

  • 安妮爱吃糖love:locale参数是什么作用?
  • 无神:对于debug很有帮助。
    string = [string stringByReplacingOccurrencesOfString:@"\\/" withString:@"/"]; // 处理\/转义字符
    string 变量从何而来?
    lancely:已经更正
    lancely:笔误,这里应该是output:wink:
  • 小星星吃KFC:product_image_filename = http://58.213.165.254/public/images/wyjk_b.jpg, 这样的内容显示成" product_image_filename" : "http:\/\/58.213.165.254\/data\/attachments\/9913bb7a-7eee-46e0-87c8-2d302323b5d8",

    数组也是用这个方法吗??
    lancely:笔误,应该是output = [output stringByReplacingOccurrencesOfString:@"\\/" withString:@"/"];
    lancely:@逝去橡皮的铅笔 在@try语句中加一句 string = [string stringByReplacingOccurrencesOfString:@"\\/" withString:@"/"]; 去除/的转义

本文标题:【iOS】打印NSDictionary为JSON格式

本文链接:https://www.haomeiwen.com/subject/hzbcvttx.html