Kabali
Kabali

Reputation: 129

Getting Invalid top-level type in JSON write iOS

Im trying to parse json responce using AFNetworking but it return me error ;

Invalid top-level type in JSON writes

but my json is as below and nothing problem regarding json format, i check JSON online and it's fine.

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

Here is my code that i used :

-(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) {
     }


}

EDIT

OK, So there's an error in my Web Service API:

I didn't set ContentType in Response header to application/Json.

Upvotes: 1

Views: 1522

Answers (4)

Ekta Padaliya
Ekta Padaliya

Reputation: 5799

May be you are missing acceptableContentTypes.

Just try to below code :

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) {

     }];

Upvotes: 1

Ketan Parmar
Ketan Parmar

Reputation: 27448

You not need to do this,

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

As you are using AFNetworking ,it has already serialized data in json object.

So remove,

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

and

you can print to directly like,

 NSLog(@"%@",responseObject)

or you can fetch your desired value from your responseObject directly.

Update :

Replace your whole code with,

   @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) {
}

Upvotes: 0

Prashant
Prashant

Reputation: 89

I think you don't need to convert data in Json format, cause AFHTTPRequestOperationManager always return in id.

Write this code in Response

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

Upvotes: 0

caldera.sac
caldera.sac

Reputation: 5098

try this to get your data inside the success block....

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);
}

Upvotes: 0

Related Questions