IOS JSON Deserialization failure - STIG/NSJSONSeri

2020-02-29 10:59发布

问题:

I want to deserialize a simple JSON I receive from a web service I run in IOS.

@"[{\"NickName\":\"James Roeiter3\",\"TempId\":\"634783760669935686\",\"LDAP\":\"XUserName15\",\"SecToken\":null},{\"NickName\":\"James Roeiter2\",\"TempId\":\"634783760654574807\",\"LDAP\":\"XUserName16\",\"SecToken\":null}]" 

I have done this many times before , I try to deserialize it both using NSJsonSerializer and also using STIG :

NSArray* array1= (NSArray*)[jsonString JSONValue]; 

NSArray* array2 = (NSArray*)[NSJSONSerialization JSONObjectWithData:jsonString   options: NSJSONReadingMutableContainers error:&error];

NOW , the issue is weird , if I copy paste the JSON from the debugger into an hard-coded string and try to parse it , it works , if I receive it in runtime , it fails , STIG says it JSON cannot start with '[' . I tried going through all the characters looking for null char (which I am not quite sure what it is ) but all the chars looked the same between the copy/paste and the runtime strings. I also tried formatting to UTF8 and play a bit with the formats -- also failed.

Any idea what can it be or how can it be solved ?? I will really appricate your help here as I am pretty stuck with this suppose to be simple issue but cant progress until I solve this ......

EDIT : The exact error I receive is this :

2012-07-21 23:59:31.376 Whisper.Client.IOS[1058:fe03] Error : Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (No string key for value in object around character 1.) UserInfo=0xc9632e0 {NSDebugDescription=No string key for value in object around character 1.}

Best of regards to you all,

James

回答1:

Ok ,the problem was the escape character and the quote character \", this is why when copying and pasting it as hard code it worked because when hardcoded the compiler reads only the quote " character. This can be very annoying if someone gets into this issue in the future : The problem is that the server url encoded the data (C# server side) , IOS url decode is known for its weakness and apprenlty does not remove the \" character from the string.

This was my current IOS decoding code :

json = [json stringByReplacingOccurrencesOfString:@"+" withString:@" "];
json = [json stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
json = [json stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:@""];
int lastChar = [json length]-1;
json = [json stringByReplacingCharactersInRange:NSMakeRange(lastChar,1) withString:@""];
json = [json stringByReplacingOccurrencesOfString:@"\\" withString:@""];
return  json;

If first remove the quotes from the beginning and end of the json , then I remove all the \ chars before the " chars.

This appears to be working smoothly now , if you think I am doing something wrong please correct me .

Hope that will help someone someday.

Cheers ,

James



标签: ios xcode json