因项目需要,经常需要打印服务器返回的json数据,而xcode打印的一般是转化成字典后的数据,看着虽然明了,但是却不是json格式的数据。我们一般需要拿到json数据去生成对应的模型的属性(当模型属性很多时),那么问题就来了,如何在控制台打印出json格式的数据呢?经研究,通过结合MJExtension,使用MJExtension拿到字典的json字符串,然后再通过自己写的这个方法,即可方便的在控制台输出格式化后的json数据,无需再拷贝数据到浏览器或者其他地方进行格式化了。纯属个人一点想法,如有错误欢迎指正。代码如下:
NSString *jsonStr = [Model mj_JSONString];
上面的方法拿到json字符串,然后调用下面的方法,来在xcode控制台进行输出格式化后的json:
[self formatJsonStr: jsonStr];
NSInteger depth = 0;
NSString *space = @" ";
NSMutableString *formated = [NSMutableString string];
[formated appendString:@"\n"];
for (int i=0; i<jsonStr.length; i++) {
NSString *c = [NSString stringWithFormat:@"%@",[jsonStr substringWithRange:NSMakeRange(i, 1)]];
if ([c isEqualToString:@"{"]) {
depth+=1;
[formated appendString:c];
[formated appendString:@"\n"];
for (int j=0; j<depth; j++) {
[formated appendString:space];
}
}else if ([c isEqualToString:@"}"]) {
depth-=1;
[formated appendString:@"\n"];
for (int j=0; j<depth; j++) {
[formated appendString:space];
}
[formated appendString:c];
}else if ([c isEqualToString:@","]) {
[formated appendString:c];
[formated appendString:@"\n"];
for (int j=0; j<depth; j++) {
[formated appendString:space];
}
}else if ([c isEqualToString:@"["]) {
depth+=1;
[formated appendString:c];
[formated appendString:@"\n"];
for (int j=0; j<depth; j++) {
[formated appendString:space];
}
}else if ([c isEqualToString:@"]"]) {
depth-=1;
[formated appendString:@"\n"];
for (int j=0; j<depth; j++) {
[formated appendString:space];
}
[formated appendString:c];
}else{
[formated appendString:c];
}
}
NSLog(@"%@",formated);
}```
网友评论