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

时间:2016-08-03 04:28:08

标签: ios objective-c afnetworking java-api

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

  

JSON写入中的顶级类型无效

但是我的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标头中将ContentType设置为application/Json.

4 个答案:

答案 0 :(得分:1)

可能是您缺少 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) {

     }];

答案 1 :(得分:0)

我认为您不需要以Json格式转换数据,因为AFHTTPRequestOperationManager始终以id身份返回。

将此代码写入Response

NSMutableArray * dataArray = [NSMutableArray new]; dataArray = [responseObject mutableCopy]

答案 2 :(得分:0)

你不需要这样做,

 jsonData = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:&writeError];

当您使用AFNetworking时,它已经在json对象中序列化了数据。

删除,

 {
            jsonData = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:&writeError];
        }

你可以直接打印,

 NSLog(@"%@",responseObject)

或者您可以直接从responseObject获取所需的值。

更新:

替换整个代码
   @try {


    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];

    AFURLSessionManager *managers = [[AFURLSessionManager alloc]initWithSessionConfiguration:configuration];



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

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



    AFHTTPRequestSerializer *requestSerializer = [AFHTTPRequestSerializer serializer];


    NSMutableURLRequest *request = [requestSerializer requestWithMethod:@"POST" URLString:setUrl parameters:parameter error:nil];

    [[managers dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {

        NSLog(@"response Object : %@",responseObject);

    }]resume];
}
@catch (NSException *exception) {
}

答案 3 :(得分:0)

尝试此操作以将数据放入成功块....

NSDictionary *allresult = (NSDictionary *)responseObject;
NSDictionary *Result = [allresult objectForKey:@"Result"];
NSArray *roomDetail = [Result objectForKey:@"RoomDetail"];

for(NSDictionary *rooms in roomDetail)
{
    NSString *roomname = [rooms objectForKey:@"RoomName"];
    NSString *naturalName = [rooms objectForKey:@"NaturalName"];
    NSLog(@"roomname : %@ ---> naturalname : %@", roomname, naturalName);
}