使用Asihttprequest和Json框架解析iPhone上的JSON数据

3

我一直在学习如何使用JSON框架和ASIHTTPRequest来解析iOS中的JSON。我已经通过Twitter Feeds和社区教程中的自定义Feed进行了测试,一切进展顺利。

然后我想测试使用Microsoft Odata Service for Northwind db。您可以在此处查看JSON结果:

http://jsonviewer.stack.hu/#http://services.odata.org/Northwind/Northwind.svc/Products%281%29?$format=json

现在,我正在努力弄清楚如何仅解析产品名称。有人能指点我吗?

在我的requestFinished中,我有这个:

- (void)requestFinished:(ASIHTTPRequest *)request
{    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    NSString *responseString = [request responseString];
    NSDictionary *responseDict = [responseString JSONValue];

    //find key in dictionary
    NSArray *keys = [responseDict allKeys];

    NSString *productName = [responseDict valueForKey:@"ProductName"];
    NSLog(@"%@",productName);
}

日志中显示我有 null。

如果我将 valueForKey 的值更改为 @"d",我会得到整个有效载荷,但我只想要 productName。

我正在使用的服务 URL 是:

http://servers.odata.org/Northwind/Northwind.svc/Products(1)?$format=json

1个回答

3
根据您提供的链接,您的JSON格式如下:
{
  "d": {
    ...
    "ProductName": "Chai",
    ...
  }
}

在顶层,您只有一个键:"d"。如果您这样做:

NSString *productName = [responseDict valueForKey:@"ProductName"];

它会返回 nil 。你需要深入层次结构:
NSDictionary *d = [responseDict valueForKey:@"d"];
NSString *productName = [d valueForKey:@"ProductName"];

或者简单地说:
NSString *productName = [responseDict valueForKeyPath:@"d.ProductName"];

非常准确。在外层添加“d”作为响应的包装似乎是.NET/Microsoft的一种常见做法。 - JosephH
太好了!非常感谢。在 d 中包装很奇怪,不过没关系。 - TheTiger
快速更新 - 我已经切换到使用JSONkit,但上面的代码返回null。有什么想法吗? - TheTiger
我已经检查过我的JSON是否正确返回,使用LOG语句一切看起来都很好,但是我没有得到预期的结果 - JSON与上面相同。 - TheTiger
好的,我明白了 - 我需要使用jsonkit将它更改为以下内容:NSString *productName = [responseDict valueForKeyPath:@"d.results.ProductName"]; - TheTiger

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接