尝试在调试时弄清楚如何从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)
不会输出任何内容。
答案 0 :(得分:1)
尝试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";
}
答案 1 :(得分:1)
e print(String(data: JSONSerialization.data(withJSONObject: JSONSerialization.jsonObject(with: data, options: []), options: .prettyPrinted), encoding: .utf8)!)
答案 2 :(得分:0)
`// 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)
}`
答案 3 :(得分:0)
这是给你的objective-c代码。你可以翻译它。
类别(objc) -> 扩展(swift)
NSLog(objc) -> 打印(swift)
类似的东西。
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 (PrettyPrint)
+ (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 = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error];
if (jsonObject == nil) {
return @"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]]);
可能你会在日志中得到这些结果。