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;
Seems I needed to add the JSON Serializer to my request.