gpt4 book ai didi

ios - AFNetworking GET 请求 - 无法将 responseObject 转换为 NSDictionary

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:43:41 25 4
gpt4 key购买 nike

我尝试了多个选项将 responseSerializer 设置为 JSON 但我无法将 responseObject 转换为 NSDictionary。问题是我得到的响应是 NSData

    NSString *baseURLString = @"Your URL?";
NSString *str = @"adult=false&gender=male";

NSString *url = [NSString stringWithFormat:@"%@%@",baseURLString,str];

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
// do whatever you'd like here; for example, if you want to convert
// it to a string and log it, you might do something like:

NSLog(@"responseObject %@",responseObject);

NSString *jsonString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"%@", jsonString);


NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseObject
options:NSJSONReadingMutableContainers
error:&error];
NSLog(@"json %@",json);

if (error) {
NSLog(@"%@",[error description]);
}



} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];

这个 NSLog(@"%@",[error description]); 给出错误如下:

Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. 
(Cocoa error 3840.)" (Garbage at end.)
UserInfo=0xa7c5440 {NSDebugDescription=Garbage at end.}

最佳答案

您的 JSON 最后返回时带有垃圾。

enter image description here您应该修复您的网络服务,使其不在 JSON 的末尾嵌入时间戳和语言。如果您无法更改您的网络服务,请使用以下方法从您的 json 中删除尾随垃圾,然后再次使用 NSJSONSerialization 进行解析。

NSRange range = [jsonString rangeOfString:@"}" options:NSBackwardsSearch];
jsonString = [jsonString substringToIndex:range.location + 1];

然后将清理后的 jsonString 解析为 NSDictionary:

NSData *newJSONData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:newJSONData
options:NSJSONReadingMutableContainers
error:&error];
NSLog(@"json %@",json);

它应该工作得很好。

关于ios - AFNetworking GET 请求 - 无法将 responseObject 转换为 NSDictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22370420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com