无法正确格式化NSString for JSON

时间:2010-05-14 12:47:22

标签: iphone json ipad nsstring nsdictionary

将我的NSStrings处理成有效的JSON字符串时遇到一些麻烦。

NSString *version       = @"1.1";
NSString *callMethod    = @"auth.login";
NSString *paramsConfig  = [NSString stringWithFormat:@"{\"email\":\"%@\",\"password\":\"%@\"}", usernameString, passwordString];

int queryId     = arc4random()% 10000000;

NSDictionary *userData          = [NSDictionary dictionaryWithObjectsAndKeys:version, @"version", callMethod, @"method", [NSNumber numberWithInt:queryId], @"id", paramsConfig, @"params", nil];
NSString* jsonString            = [userData JSONRepresentation];

预期的JSON字符串:

{"version":"1.1","params":"{"email":"s","password":"s"}","id":12345678,"method":"auth.login"}

实际JSON字符串:

{"version":"1.1","params":"{\"email\":\"s\",\"password\":\"s\"}","id":12345678,"method":"auth.login"}

不确定我哪里出错了。有什么想法吗?

由于

萨姆

1 个答案:

答案 0 :(得分:1)

您的JSON的paramsConfig部分是一个字符串,并将被转义。 IIRC,如果您将paramsConfig更改为NSDictionary,然后在那里设置电子邮件和密码的值,将输出正确的JSONRepresentation。