繁体   English   中英

在Objective-C中解析JSON

[英]Parse JSON in Objective-C

我是Objective-C和JSON的新手,所以我对如何执行此操作感到困惑。 我查看了教程,并确保我的JSON有效。

我有一个SQL Server数据库,我正在尝试通过解析JSON访问。 我已经检查以确保我的JSON有效。 每当我尝试解析JSON是Objective-C时,它总是返回null。

这是我的JSON:

[
{
    "ID": 1,
    "Username": "Cray",
    "Password": "fake",
    "Active": 0,
    "LastLogin": null
}
]

这是我的Objective-C代码:

NSString *urlString = [NSString stringWithFormat:@"http://quacknasty.com/service.php"];

NSURL *url = [NSURL URLWithString:urlString];

NSData *data = [NSData dataWithContentsOfURL:url];

NSError *error;

NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

NSLog(@"test%@", json);

当我执行NSLog时, json始终返回null

简单的一种:在浏览器中打开URL。 您将看到您没有有效的JSON:

Conneection established. 
[{"ID":1,"Username":"Cray","Password":"fake","Active":0,"LastLogin":null}]

您必须删除已Connection established.\\nConnection established.\\n的回显Connection established.\\n

编辑我:您必须使用NSArray作为根对象,因为JSON字符串以[]开头

编辑II:此外,您应按如下所示设置正确的HTTP标头字段:

header('Content-Type: application/json; charset=utf-8');

网址请求。 响应是:

Conneection established. 
<br />[{"ID":1,"Username":"Cray","Password":"fake","Active":0,"LastLogin":null}]

不是json格式

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM