Convert NSString to NSDictionary bug

185 views Asked by At

I have a string from server, and when i try to convert it to NSDictionary - i get "nil". When i try to write same NSString by myself - it's ok!

I get from server encoded string, then i use "AES256DecryptWithKey" from NSString+AESCrypt.h to decrypt, and get NSString, this string i convert to NSData and then try to get NSDictionary

NSString *str = @"{\"error\":{\"password\":[\"Error wrong!\"]}}"; //string written by myself

NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData
                                                         options:kNilOptions
                                                           error:&error];

This code work, but then i get this string from server - not(

NSData log (message from server) - <7b226572 726f7222 3a7b2270 61737377 6f726422 3a5b22d0 9dd0b5d0 bfd180d0 b0d0b2d0 b8d0bbd1 8cd0bdd1 8bd0b920 656d6169 6c20d0b8 d0bbd0b8 20d0bfd0 b0d180d0 bed0bbd1 8c225d7d 7d000000>

NSData log (my string) - <7b226572 726f7222 3a7b2270 61737377 6f726422 3a5b22d0 9dd0b5d0 bfd180d0 b0d0b2d0 b8d0bbd1 8cd0bdd1 8bd0b920 656d6169 6c20d0b8 d0bbd0b8 20d0bfd0 b0d180d0 bed0bbd1 8c225d7d 7d>

If i NSLog string from server, it - {"error":{"password":["Error wrong!"]}} , string without "\"

Then i "po &error.localizedDescription" - error: address of property expression requested error: 1 errors parsing expression

Then i "po error.localizedDescription" - Printing description of error: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Garbage at end.) UserInfo=0x7f9940497550 {NSDebugDescription=Garbage at end.}

What it can be??

1

There are 1 answers

5
Mats On BEST ANSWER

The error message says:

Garbage at end.

So, comparing your data and the data from the server, we see:

Test string data:
<7b226572 726f7222 3a7b2270 61737377
 6f726422 3a5b22d0 9dd0b5d0 bfd180d0
 b0d0b2d0 b8d0bbd1 8cd0bdd1 8bd0b920
 656d6169 6c20d0b8 d0bbd0b8 20d0bfd0
 b0d180d0 bed0bbd1 8c225d7d 7d>

Server data:
<7b226572 726f7222 3a7b2270 61737377
 6f726422 3a5b22d0 9dd0b5d0 bfd180d0
 b0d0b2d0 b8d0bbd1 8cd0bdd1 8bd0b920
 656d6169 6c20d0b8 d0bbd0b8 20d0bfd0
 b0d180d0 bed0bbd1 8c225d7d 7d000000>

The decoded data is 3 bytes longer. Maybe it is padded ahead of the encryption or as an effect of your decryption due to some padding parameter. As a workaround you could remove the stray 000000.