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:
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
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"];