无法正确格式化 NSString 为 JSON
将我的 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"}
不太确定我哪里出错了。有什么想法吗?
谢谢萨姆
Having a little trouble processing my NSStrings into a valid JSON string.
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];
Expected JSON string:
{"version":"1.1","params":"{"email":"s","password":"s"}","id":12345678,"method":"auth.login"}
Actual JSON string:
{"version":"1.1","params":"{\"email\":\"s\",\"password\":\"s\"}","id":12345678,"method":"auth.login"}
Not really sure where I'm going wrong. Any thoughts?
Thanks
Sam
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
JSON 的 paramsConfig 部分是一个字符串,并且将被转义。 IIRC,如果您将 paramsConfig 更改为 NSDictionary,然后在那里设置电子邮件和密码的值,将输出正确的 JSONRepresentation。
The paramsConfig part of your JSON is a string, and will be escaped as such. IIRC, if you change paramsConfig to be a NSDictionary, then set the values for email and password there, the correct JSONRepresentation will be outputted.