0

我是iOS开发的新手。当我用 NSJSONSerialization 处理 json 时,我发现对我来说确实是个问题。

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

输出是:

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;

带有“\”的数据部分不能是 NSDictionary 对象

那么我应该怎么做才能使它正确呢?

对不起我的英语不好。

4

1 回答 1

1

无论出于何种原因,“data”的值都不是 JSON 字典,而是包含 JSON 数据的字符串。您可以通过JSONObjectWithData再次应用此字符串并替换字典中的值来解决此问题:

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);

输出:

dict: {
    data =     {
        rand = 5360;
        sessionID = 9217e5df3db6b4b4aa3eed800890069f;
        sessionName = sid;
        title = "";
    };
    md5 = 292ee1e78628fc6360c647e938c4f1ea;
    status = success;
}
于 2013-03-18T14:16:42.413 回答