AFNetworking posts JSON arrays as multiple single-entry dictionaries

前端 未结 4 1578
予麋鹿
予麋鹿 2020-12-19 13:26

I\'m having a similar issue to the one discussed here.

I\'m attempting to post JSON to a server.

Here\'s the Objective-C code that should work, but

相关标签:
4条回答
  • 2020-12-19 14:13

    I too had this issue recently, I had the following parameters to be sent to the server, but the "feature" array was breaking into 4 parts rather than just 2 dictionaries.

            { "description": "Temporary Description",   
              "name": "Product Name",  
              "feature": [
                {
                  "fkey": "FT1",
                  "fvalue": "FD1"
                },
                {
                  "fkey": "FT2",
                  "fvalue": "FD2"
                }   
             ] 
        }
    

    So I changed the

    AFURLRequestSerialisation.m

    replaced this line in AFQueryStringPairsFromKeyAndValue(NSString *key, id value) method

    [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue([NSString stringWithFormat:@"%@[]", key], nestedValue)];
    

    with

    [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue([NSString stringWithFormat:@"%@[%i]", key, [array indexOfObject:nestedValue]], nestedValue)];
    

    And this did the trick. I hope this might help someone.

    0 讨论(0)
  • 2020-12-19 14:15

    I'm using POST, so query strings are not involved. But maybe the limitation exists with POST data as well?

    The limitation is not on POST, it's URL form encoding. I go on to say that you should encode as JSON, which you can do with the following configuration change to your manager:

    manager.requestSerializer = [AFJSONRequestSerializer serializer];.

    Also, unless you're actually constructing a multi-part request, don't use the constructingBodyWithBlock version of that method.

    0 讨论(0)
  • 2020-12-19 14:28

    Ugly solutions are for the weak minded: How can I POST an NSArray of NSDictionaries inside an NSDictionary without problems?

    The answer to this post contains all you need.

    0 讨论(0)
  • 2020-12-19 14:29

    I just dealt with the same issue and the only solution I could find was to create a dictionary out of the array. There must be a better way, this is pretty ugly...

        NSMutableDictionary *arrayDict = [[NSMutableDictionary alloc] init];
        int counter = 0;
        for (NSMutableDictionary *arrayItem in arrayToSend) {
            [arrayDict setObject:arrayItem forKey:[NSNumber numberWithInt:counter]];
            counter++;
        }
    

    Otherwise everything got flattened sort of. I use AFJSONRequestSerializer, but that doesn't seem to matter.

    0 讨论(0)
提交回复
热议问题