Parse JSON data using Asihttprequest and the Json framework for iphone

拟墨画扇 提交于 2019-12-21 05:34:08

问题


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.

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?

On my requestFinished i have this:

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

In the log I have null.

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

The service URL I am using is:

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


回答1:


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

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

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

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

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

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

Or simply:

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


来源:https://stackoverflow.com/questions/6974004/parse-json-data-using-asihttprequest-and-the-json-framework-for-iphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!