如何漂亮打印 json 来自 API 在调试器中调用的响应?
How to prettyPrint json response from API call in debugger?
试图弄清楚如何在调试时漂亮地打印来自 API 我的响应的 json 值:
let session = URLSession(configuration: .default)
let task = session.dataTask(with: urlRequest) { data, response, error in
completion(data, response, error)
}
在调试器中,如果我执行 po 数据,这就是我得到的结果:
如何打印出数据对象中的实际 json 结构?希望看到这样的东西:
{ "firstName" : "John",
"lastName" : "Doe",
...
}
po debugPrint(data)
在这种情况下不输出任何内容。
试试 JSONSerialization
,像这样:
let url = URL(string: "http://date.jsontest.com")
var request : URLRequest = URLRequest(url: url!)
request.httpMethod = "GET"
let dataTask = URLSession.shared.dataTask(with: request) {
data,response,error in
do {
if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {
print(jsonResult)
}
} catch let error {
print(error.localizedDescription)
}
}
dataTask.resume()
其中 jsonResult
将打印出以下内容:
{
date = "02-19-2018";
"milliseconds_since_epoch" = 1519078643223;
time = "10:17:23 PM";
}
// given raw JSON, return a usable Foundation object
private func convertDataWithCompletionHandler(_ data: Data, completionHandlerForConvertData: (_ result: AnyObject?, _ error: NSError?) -> Void) {
var parsedResult: AnyObject! = nil
do {
parsedResult = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as AnyObject
} catch {
let userInfo = [NSLocalizedDescriptionKey : "Could not parse the data as JSON: '\(data)'"]
completionHandlerForConvertData(nil, NSError(domain: "convertDataWithCompletionHandler", code: 1, userInfo: userInfo))
}
completionHandlerForConvertData(parsedResult, nil)
}
e print(String(data: JSONSerialization.data(withJSONObject: JSONSerialization.jsonObject(with: data, options: []), options: .prettyPrinted), encoding: .utf8)!)
这是给你的 objective-c 代码。
NSString+PrettyPrint.h
@interface NSString (PrettyPrint)
+ (NSString * _Nonnull)prettifiedJsonStringFromData:(nullable NSData *)data;
+ (NSString * _Nonnull)prettifiedStringFromDictionary:(nullable NSDictionary *)dictionary;
@end
NSString+PrettyPrint.m
#import "NSString+PrettyPrint.h"
@implementation NSString (Prettified)
- (NSString *)trimForCount:(NSUInteger)count {
return self.length > count ? [self substringWithRange:NSMakeRange(0, count)] : self;
}
+ (NSString *)prettifiedStringFromDictionary:(nullable NSDictionary *)dictionary {
if (dictionary == nil) { return @"nil"; }
NSMutableString *returnStr = [NSMutableString stringWithString:@"[ \n"];
for (NSString *key in dictionary) {
[returnStr appendFormat:@" %@: %@,\n", key, [dictionary valueForKey:key]];
}
[returnStr appendFormat:@"]"];
return returnStr;
}
+ (NSString *)prettifiedJsonStringFromData:(nullable NSData *)data {
if (data == nil) { return @"nil"; }
NSData *jsonData;
NSError *error = nil;
NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
id jsonObject;
@try {
jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error];
} @catch(id anException) {
return anException ? [NSString stringWithFormat:@"Json Parse Exception: %@", anException] : jsonStr ? jsonStr : @"json parse exception";
}
if (jsonObject == nil) {
return jsonStr ? jsonStr : @"nil (json object from data)";
} else {
BOOL isValidJsonObject = [NSJSONSerialization isValidJSONObject:jsonObject];
if (isValidJsonObject) {
NSData *finalData = [NSJSONSerialization dataWithJSONObject:jsonObject options:NSJSONWritingPrettyPrinted error:&error];
//TODO: error description
NSString *prettyJson = [[NSString alloc] initWithData:finalData encoding:NSUTF8StringEncoding];
return prettyJson;
} else {
return [NSString stringWithFormat:@"%@\n%@", jsonStr, @" (⚠️ Invalid json object ⚠️)\n"];
}
}
}
@end
然后调用方法,
ex1。打印正文、响应等的 NSData
NSLog(@"body: %@", [NSString prettifiedJsonStringFromData:[request HTTPBody]]);
ex2。打印 NSDictionary
NSLog(@"headers: %@", [NSString prettifiedStringFromDictionary:[request allHTTPHeaderFields]]);
您可能会在日志中得到这些结果。
编辑日志:
编辑于220112,防止异常
试图弄清楚如何在调试时漂亮地打印来自 API 我的响应的 json 值:
let session = URLSession(configuration: .default)
let task = session.dataTask(with: urlRequest) { data, response, error in
completion(data, response, error)
}
在调试器中,如果我执行 po 数据,这就是我得到的结果:
如何打印出数据对象中的实际 json 结构?希望看到这样的东西:
{ "firstName" : "John", "lastName" : "Doe", ... }
po debugPrint(data)
在这种情况下不输出任何内容。
试试 JSONSerialization
,像这样:
let url = URL(string: "http://date.jsontest.com")
var request : URLRequest = URLRequest(url: url!)
request.httpMethod = "GET"
let dataTask = URLSession.shared.dataTask(with: request) {
data,response,error in
do {
if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {
print(jsonResult)
}
} catch let error {
print(error.localizedDescription)
}
}
dataTask.resume()
其中 jsonResult
将打印出以下内容:
{
date = "02-19-2018";
"milliseconds_since_epoch" = 1519078643223;
time = "10:17:23 PM";
}
// given raw JSON, return a usable Foundation object
private func convertDataWithCompletionHandler(_ data: Data, completionHandlerForConvertData: (_ result: AnyObject?, _ error: NSError?) -> Void) {
var parsedResult: AnyObject! = nil
do {
parsedResult = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as AnyObject
} catch {
let userInfo = [NSLocalizedDescriptionKey : "Could not parse the data as JSON: '\(data)'"]
completionHandlerForConvertData(nil, NSError(domain: "convertDataWithCompletionHandler", code: 1, userInfo: userInfo))
}
completionHandlerForConvertData(parsedResult, nil)
}
e print(String(data: JSONSerialization.data(withJSONObject: JSONSerialization.jsonObject(with: data, options: []), options: .prettyPrinted), encoding: .utf8)!)
这是给你的 objective-c 代码。
NSString+PrettyPrint.h
@interface NSString (PrettyPrint)
+ (NSString * _Nonnull)prettifiedJsonStringFromData:(nullable NSData *)data;
+ (NSString * _Nonnull)prettifiedStringFromDictionary:(nullable NSDictionary *)dictionary;
@end
NSString+PrettyPrint.m
#import "NSString+PrettyPrint.h"
@implementation NSString (Prettified)
- (NSString *)trimForCount:(NSUInteger)count {
return self.length > count ? [self substringWithRange:NSMakeRange(0, count)] : self;
}
+ (NSString *)prettifiedStringFromDictionary:(nullable NSDictionary *)dictionary {
if (dictionary == nil) { return @"nil"; }
NSMutableString *returnStr = [NSMutableString stringWithString:@"[ \n"];
for (NSString *key in dictionary) {
[returnStr appendFormat:@" %@: %@,\n", key, [dictionary valueForKey:key]];
}
[returnStr appendFormat:@"]"];
return returnStr;
}
+ (NSString *)prettifiedJsonStringFromData:(nullable NSData *)data {
if (data == nil) { return @"nil"; }
NSData *jsonData;
NSError *error = nil;
NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
id jsonObject;
@try {
jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error];
} @catch(id anException) {
return anException ? [NSString stringWithFormat:@"Json Parse Exception: %@", anException] : jsonStr ? jsonStr : @"json parse exception";
}
if (jsonObject == nil) {
return jsonStr ? jsonStr : @"nil (json object from data)";
} else {
BOOL isValidJsonObject = [NSJSONSerialization isValidJSONObject:jsonObject];
if (isValidJsonObject) {
NSData *finalData = [NSJSONSerialization dataWithJSONObject:jsonObject options:NSJSONWritingPrettyPrinted error:&error];
//TODO: error description
NSString *prettyJson = [[NSString alloc] initWithData:finalData encoding:NSUTF8StringEncoding];
return prettyJson;
} else {
return [NSString stringWithFormat:@"%@\n%@", jsonStr, @" (⚠️ Invalid json object ⚠️)\n"];
}
}
}
@end
然后调用方法,
ex1。打印正文、响应等的 NSData
NSLog(@"body: %@", [NSString prettifiedJsonStringFromData:[request HTTPBody]]);
ex2。打印 NSDictionary
NSLog(@"headers: %@", [NSString prettifiedStringFromDictionary:[request allHTTPHeaderFields]]);
您可能会在日志中得到这些结果。
编辑日志:
编辑于220112,防止异常