使用Asihttprequest和iphone的Json框架解析JSON数据 [英] Parse JSON data using Asihttprequest and the Json framework for iphone

查看:149
本文介绍了使用Asihttprequest和iphone的Json框架解析JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在学习如何使用JSON框架和ASIHTTPRequest for iOS解析JSON。我已经使用Twitter提要测试,也通过社区教程测试自定义提要。一切顺利。

I've been learning how to parse JSON using the JSON framework and ASIHTTPRequest for iOS. I've tested using twitter feeds and also a custom feed through a community tutorial. All is going well.

然后我想我将使用Northwind db的Microsoft Odata服务进行测试。你可以在这里查看json结果:

I then thought I'll test using the Microsoft Odata Service for Northwind db. You can view the json results here:

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

现在我正在努力解决如何解析产品名称的问题。任何人都能指出我正确的方向吗?

Now I've struggling to work out how to parse just the product name. Can anyone point me in the right direction?

根据我的要求完成我有这个

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

在日志中我有空。

如果我将valueforKey更改为 @d我得到了整个有效负载,但我只想要productName。

If I change the valueforKey to @"d" I get the whole of the payload but I just want the productName.

我使用的服务网址是:

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

推荐答案

根据您提供的链接,您的JSON格式如下:

According to the link you have provided, your JSON has the following format:

{
  "d": {
    ...
    "ProductName": "Chai",
    ...
  }
}

在顶层,你只有一把钥匙:d。如果你这样做:

At the top level, you only have one key: "d". If you do this:

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

它将返回 nil 。您需要深入了解层次结构:

It will return nil. You need to get deeper in the hierarchy:

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

或者只是:

NSString *productName = [responseDict valueForKeyPath:@"d.ProductName"];

这篇关于使用Asihttprequest和iphone的Json框架解析JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆