我正在使用 NSURLSession
从用 PHP 编写的从 MYSQL 数据库中提取的 API 接收 JSON。
对于来自某个 MYSQL 表的一个查询,手机似乎无法读取 API 生成的 JSON,即使它在 Postman 和浏览器中看起来很好。事实上,我配置了另一个表和查询来生成完全相同的 JSON,手机可以毫无问题地读取它。我唯一能想到的是,问题表和查询中的 JSON 中存在不可见的字符,这些字符正在抛出问题。我比较了 Postman 中两个表的查询标题,它们是相同的。
是否已知 NSURLSession 存在隐藏字符等问题?
这是 JSON 在 Postman 中打印出来的样子:
{
"comment": [
{
"response": "you haven't been paying attention"
}
]
}
这是浏览器显示的内容:
"comment":[{"response":"you haven't been paying attention"}]}
这是 Xcode 控制台显示的内容:
comment = "0(NSNull)"
这是 Objective-C 代码:
NSURL *dataUrl = [NSURL URLWithString:surl];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *data =[session dataTaskWithURL:dataUrl completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSData *jsonFeed = data;
NSLog(@"jsonFeed is%@",jsonFeed);
if (data != nil) {
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:jsonFeed
options:kNilOptions
error:&error];
NSLog(@"json in async is:%@",json);
}
}];
[data resume];
最佳答案
我怀疑您传递了错误的 Content-Type
。请在请求中传递正确的 Content-Type
。
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
使用 NSMutableURLRequest
创建请求,这是一个很好的请求示例,请检查这个。 Link
关于ios - IOS 应用程序收到的来自 API 的 JSON 与在 Postman 或浏览器中查看的 JSON 之间存在差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56729407/