gpt4 book ai didi

ios - 在 JSON 中获取无效的顶级类型写入 iOS

转载 作者:行者123 更新时间:2023-11-29 11:56:51 25 4
gpt4 key购买 nike

我尝试使用 AFNetworking 解析 json 响应,但它返回错误;

Invalid top-level type in JSON writes

但是我的json如下,关于json格式没有问题,我在网上查了json没问题。

{
"Result": {
"RoomDetail": [
{
"RoomName": "crs",
"NaturalName": "aaa"
},
{
"RoomName": "ios",
"NaturalName": "ios"
}
]
}
}

这是我使用的代码:

-(void)CallRoom
{
@try {
AFHTTPRequestOperationManager *managers = [AFHTTPRequestOperationManager manager];

NSMutableDictionary *parameter = [[NSMutableDictionary alloc]initWithObjectsAndKeys:
@"bhavin",@"userName",
nil];

NSString *setUrl = [NSString stringWithFormat:@"http://localhost/OpenFire-Chat/getChatRoomsByUser.htm"];

managers.responseSerializer = [AFHTTPResponseSerializer serializer];

[managers POST:setUrl parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {

NSError *writeError = nil;
NSData *jsonData;

//if ([NSJSONSerialization isValidJSONObject:responseObject])
{
jsonData = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:&writeError];
}


NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&writeError];
}failure:^(AFHTTPRequestOperation *operation, NSError *error) {

NSLog(@"Error: %@", error);
}];

}
@catch (NSException *exception) {
}


}

编辑

好的,所以我的 Web 服务 API 中有一个错误:

我没有将 Response header 中的 ContentType 设置为 application/Json.

最佳答案

可能是您缺少 acceptableContentTypes

只需尝试下面的代码:

AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
[serializer setStringEncoding:NSUTF8StringEncoding];

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer=serializer;

manager.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"text/html",@"application/json", nil];

NSMutableDictionary *parameter = [[NSMutableDictionary alloc]initWithObjectsAndKeys:
@"bhavin",@"userName",
nil];

NSString *setUrl = [NSString stringWithFormat:@"http://localhost/OpenFire-Chat/getChatRoomsByUser.htm"];

[manager POST:setUrl parameters:parameter progress:nil success:^(NSURLSessionTask *task, id responseObject)
{
//log responseObject
} failure:^(NSURLSessionTask *operation, NSError *error) {

}];

关于ios - 在 JSON 中获取无效的顶级类型写入 iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38734429/

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