备案 控制台
学习
实践
活动
专区
工具
TVP
写文章
专栏首页 Objective-C iOS-打印 JSON 数据原格式
7 0

海报分享

iOS-打印 JSON 数据原格式

痛点

实际开发过程中,从网络上拿到的数据,再控制台打印输出时,格式是以下形式的:

{
    error = {
        errorCode = 10002;
        errorMessage = "Appkey is missing. (\U65e0appkey\U53c2\U6570)";
    status = ERROR;
}

存在着以下几点问题

  • 双引号 " " 缺失
  • unicode 编码没有显示中文
  • 当有数组情况时候,数组的中括号 [ ] --->变成可恶的圆括号了 ( )

解决办法

  • 写一个 NSDictionary Category
  • 分类里重写方法 - (NSString *)descriptionWithLocale:(id)locale
- (NSString *)descriptionWithLocale:(id)locale {
    NSString *string;
    @try {
        string = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
    } @catch (NSException *exception) {
        NSString *reason = [NSString stringWithFormat:@"reason:%@",exception.reason];
        string = [NSString stringWithFormat:@"转换失败:\n%@,\n转换终止,输出如下:\n%@",reason,self.description];
    } @finally {
    return string;
}
  • 返回数据打印样式
{
    "status" : "ERROR",
    "error" : {
        "errorMessage" : "Appkey is missing. (无appkey参数)",
        "errorCode" : 10002
}
  • 解析结果

使用方法

HQLogHelper 导入到你的项目中,然后直接运行即可。


Demo

GitHub HQLogHelper


参考:

本文参与 腾讯云自媒体分享计划 ,欢迎热爱写作的你一起参与!
本文分享自作者个人站点/博客: https://www.jianshu.com/u/1ab0fcff23e7 复制
如有侵权,请联系 cloudcommunity@tencent.com 删除。