brenjt
brenjt

Reputation: 16297

JSON data messed up in AFNetworking POST request

I am sending a request with AFNetworking for Objective-C. When I NSLog the parameters this is the object I am sending:

games = (
        {
        id = 50;
        p = 8;
        ts = 0;
        tt = ();
        tw = 0;
        ys = 35150;
        yt = {
            156424496 = "37.416669";
            156609008 = "56.661210";
            ....
            252846816 = "7.075133";
            252856944 = "61.329850";
        };
        yw = 0;
    }, ...

This is what the server receives.

games = (
        {id = 50;},
        {p = 8;},
        {ts = 0;},
        {tw = 0;},
        {ys = 35150;},
        {
            yt = {156424496 = "37.416669";};
        },
        {
            yt = {156609008 = "56.661210";};
        },
        ...
        {
            yt = {252846816 = "7.075133";};
        },
        {
            yt = {252856944 = "61.329850";};
        },
        {yw = 0;},
...

It is as if it is taking each property of my object and creating a new object with it. The worse part is that it's taking the multiple objects that are in the array and putting all properties of all objects and turning them into separate object on the same depth of the array.

Here is the code I am using to send this off:

NSArray *games = [ResourceManager getAllGames];
NSMutableArray *gamesArray = [[NSMutableArray alloc] initWithCapacity:[games count]];
for(Game *g in games)
{
    [gamesArray addObject:[g toDictionary]];
}
User *user = [ResourceManager getUser];
NSDictionary *params = [[NSDictionary alloc] initWithObjectsAndKeys:gamesArray, @"games", user.id, @"user_id", nil];
NSLog(@"PARAMS: %@", params); <- this is the first block of code above
[self postPath:API_SYNC_GAMES_URL parameters:params success:^(AFHTTPRequestOperation *operation, id JSON)
{
}

I have not been able to figure out why this would be happening, and I am all out of guesses. If someone could point me in the right direction it would be very appreciated.

UPDATE

If I post a single object rather than an array of the objects it arrives at the server successfully.

Upvotes: 2

Views: 662

Answers (2)

Vulkan
Vulkan

Reputation: 1074

Take a look at my answer here: How can I POST an NSArray of NSDictionaries inside an NSDictionary without problems?

It solves all your problems.

Upvotes: 0

brenjt
brenjt

Reputation: 16297

I was able to solve this issue by using an NSDictionary instead of an array. Each object I have has a unique key so I used that key for the NSDictionary like so:

NSMutableDictionary *gamesArray = [[NSMutableDictionary alloc] 
                                          initWithCapacity:[games count]];
for(Game *g in games)
{
    [gamesArray setObject:[g toDictionary] 
                   forKey:[NSString stringWithFormat:@"%@", g.id]];
}

That seems to have solved the issue.

Upvotes: 2

Related Questions