prettyvoid
prettyvoid

Reputation: 3686

NSJSONSerialization encoding?

I'm trying to convert my NSDictionary to a json string and then send the data to my web api via HTTPBody (POST request). I convert my dictionary to json like this:

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];

What I found is that this above method, is not encoding my data (at least special characters like ampersand is not being handled). So the data received on the server side is a mess and I can't read it properly.

For more details on what is happening, assume the following dictionary:

"salutation":"Mrs."
"companyName":"T & F LLP"
"firstName":"Tania"
"country":"Canada"

This dictionary is converted to NSData using the above method and later used like this

[request setHTTPBody:nsDataFromJson];

What do I receive on the server side? I get this

{"contact":"{\"firstName\":\"Tania\",\"salutation\":\"Mrs.\",\"company\":\"Aird 

I only get the data up to the special character & and I can only assume that this is happening because the first method I mentioned is not encoding special characters like the &

So I solved this (just for the time being) by converting the dictionary into a json string then replacing each & with %26 then creating NSData from this new string (with the special characters handled). Then I get the full body on my server.

So any idea how to properly handle this?

By the way, the same problem occurs if I use SBJSON too.

Upvotes: 1

Views: 1027

Answers (1)

kk1
kk1

Reputation: 53

It has been 3 months, so I guess the problem must have been solved by now.

The reason the received JSON data is corrupted is because the parser interpreted & (ampersand) as a part of the URL address. Borrowing some codes from this link, I wrote this function to percent-encode & and a few other characters that may get confused:

+ (NSDictionary*) percentEncodeDictionayValues:(NSDictionary*) dict
{
    NSMutableDictionary* edict=[NSMutableDictionary dictionaryWithDictionary:dict];

    NSMutableCharacterSet* URLQueryPartAllowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
    [URLQueryPartAllowedCharacterSet removeCharactersInString:@"?&=@+/'"];

    for(NSString* key in [dict allKeys])
    {
        if([dict[key] isKindOfClass:[NSString class]])
            edict[key] = [dict[key] stringByAddingPercentEncodingWithAllowedCharacters:URLQueryPartAllowedCharacterSet];
    }
    return edict;
}

So you can preprocess your NSDictionary object with this function before feeding into NSJSONSerialization, and the received data will have & and other characters preserved.

Upvotes: 0

Related Questions