0

I'm a newbie about development of iOS. And when I deal a json with NSJSONSerialization , I find something really a problem to me.

NSLog(@"response: %@", responseString);
NSData *jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
NSLog(@"dict: %@", dict);

and the output is:

2013-03-18 20:13:56.228 XXXX[3550:5003] response: {"status":"success","data":"{\"title\":\"\",\"sessionName\":\"sid\",\"sessionID\":\"9217e5df3db6b4b4aa3eed800890069f\",\"rand\":5360}","md5":"292ee1e78628fc6360c647e938c4f1ea"}
2013-03-18 20:13:56.229 XXXX[3550:5003] dict: {
data = "{\"title\":\"\",\"sessionName\":\"sid\",\"sessionID\":\"9217e5df3db6b4b4aa3eed800890069f\",\"rand\":5360}";
md5 = 292ee1e78628fc6360c647e938c4f1ea;
status = success;

with the "\" the data section cannot be a NSDictionary object

So what should I do to make it right?

Sorry for my poor English.

Puttin
  • 1,596
  • 23
  • 27

1 Answers1

1

For whatever reason, the value of "data" is not a JSON dictionary, but a string containing JSON data. You can fix this by applying JSONObjectWithData to this string again and replacing the value in the dictionary:

NSData *jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];

NSData *nestedJsonData = [[dict objectForKey:@"data"] dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *nestedDict = [NSJSONSerialization JSONObjectWithData:nestedJsonData options:NSJSONReadingMutableContainers error:nil];

[dict setObject:nestedDict forKey:@"data"];
NSLog(@"dict: %@", dict);

Output:

dict: {
    data =     {
        rand = 5360;
        sessionID = 9217e5df3db6b4b4aa3eed800890069f;
        sessionName = sid;
        title = "";
    };
    md5 = 292ee1e78628fc6360c647e938c4f1ea;
    status = success;
}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Of course, a better solution would be if the server sends proper JSON data :-) – Martin R Mar 18 '13 at 14:30
  • now I wonder how this works? Why the JSONObjectWithData will delete all these character? – Puttin Apr 01 '13 at 06:50
  • @ct455332: The escape characters are not really in the string. They are only printed by NSLog(). If you single-step the code and look at the variables you should see how it works. – Martin R Apr 01 '13 at 11:59