How do I add an NSArray of NSDictionaries to a AFJSONRequestSerializer request?

111 views Asked by At

I wrote some code to put a NS(Mutable)Dictionary in a NSArray. But after adding the dictionary to the array, it seems it creates separate dictionaries for each key-value pair. See example below.

NSMutableDictionary *info = [[NSMutableDictionary alloc] init];
[info setObject:@"123" forKey:@"user_id"];
[info setObject:@"John" forKey:@"name"];
NSArray *array = [NSArray arrayWithObject:info];

NSMutableDictionary *htmlParams = [[NSMutableDictionary alloc] init];
[htmlParams setObject:array forKey:@"users"];

expected output:

{
    "users": [
        {
            "user_id": 123,
            "name": "John
        }
    ]

}

what I get:

{
    "users": [
        {
            "user_id": 123,
        }, {
            "name": "John
        }
    ]

}

What am I doing wrong?

Thanks for your help!!

EDIT* I tried some more stuff and it seems I figured what the problem is, but it still seems weird to me.

A little background: when I log the NSDictionary, I, indeed, get the expected output. But when I send it to my back-end, it get's fucked up.

I created to new NSDictionaries (as object literals):

1:

NSDictionary *info = @{
    @[
        @{
            @"firstname": @"John",
            @"lastname": @"Doe",
        },
        @{
            @"firstname": @"Jane",
            @"lastname": @"Da",
        },
    ]
};

2:

NSDictionary *info = @{
        @0: @{
                @"firstname": @"John",
                @"lastname": @"Doe",
        },
        @1: @{
                @"firstname": @"Jane",
                @"lastname": @"Da",
        },
};

1: goes wrong, every line in the array is outputted as a different dictionary in my backend. 2: behaves as expected.

I have no idea what causes this problem, but I'm pretty sure it isn't my package (AFNetworking) and also not my back-end (Symfony PHP).

EDIT *

seems I needed to add the Json Serializer to my request.

AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
[serializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[serializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
manager.requestSerializer = serializer;
2

There are 2 answers

0
anche On BEST ANSWER

Seems I needed to add the JSON Serializer to my request.

AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
[serializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[serializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
manager.requestSerializer = serializer;
0
dahiya_boy On

I run your code in my x-code i got below output:

{
users =     (
            {
        name = John;
        "user_id" = 123;
    }
);

}

And this is what you'r expecting, I don't think there is any wrong in your code, so check again because otherwise, i also get the wrong answer .