I am getting data from the Yummly API and I would like to use it as though it were serialized JSON data. However, it is currently a string, and I cannot figure out how to turn it to data correctly. The code is as following:

NSString *searchParameters = @"basil"; //should be from text box
//NSError *error1 = nil;
NSString *searchURLName = [@"http://api.yummly.com/v1/api/recipes?_app_id=myAPIId&_app_key=myAPIkey&" stringByAppendingString:searchParameters];

NSURL *searchURL = [NSURL URLWithString:searchURLName]; 
NSString *searchResults = [NSString stringWithContentsOfURL:searchURL encoding:NSUTF8StringEncoding error:nil];
// Here, the search results are formatted just like a normal JSON file, 
// For example:
/* [
   "totalMatchCount":777306,
   "facetCounts":{}
    ]
*/
// however it is a string, so I tried to  convert it to data 

NSData *URLData  = [searchResults dataUsingEncoding:NSUTF8StringEncoding];
URLData = [URLData subdataWithRange:NSMakeRange(0, [URLData length] - 1)];

_searchArray = [NSJSONSerialization JSONObjectWithData:URLData options:NSJSONReadingMutableContainers error:nil];

Somewhere over the last four lines, it didn't do what it was supposed to and there is no data in the data object. Any advice or quick hints in the right direction are much appreciated! Thank you1

有帮助吗?

解决方案

Look at the error being returned from the NSJSONSerialization object like

NSError *error;
_searchArray = [NSJSONSerialization JSONObjectWithData:URLData options:NSJSONReadingMutableContainers error:&error];
NSLog(@"%@", error);

This might give you a hint of what's wrong. This should work though. And why exactly are you doing URLData = [URLData subdataWithRange:NSMakeRange(0, [URLData length] - 1)];? You don't need to copy the data, if that's why you're doing that.

Plus, it seems like you're assuming to get an array as the top level object (judging by

/* [
   "totalMatchCount":777306,
   "facetCounts":{}
    ]
*/

but this is a dictionary. Basically you probably want a dictionary, not array. This it should be

/* {
   "totalMatchCount":777306,
   "facetCounts":{}
    }
*/

But the error getting returned will tell you that.

其他提示

It looks like you're over-complicating things a bit. You do not need to bring in this data as an NSString at all. Instead, just bring it in as NSData and hand that to the parser.

Try:

NSString *searchParameters = @"basil"; //should be from text box
NSString *searchURLName = [@"http://api.yummly.com/v1/api/recipes?_app_id=myAPIId&_app_key=myAPIkey&" stringByAppendingString:searchParameters];

NSURL *searchURL = [NSURL URLWithString:searchURLName]; 

NSData *URLData  = [NSData dataWithContentsOfURL:searchURL];

_searchArray = [NSJSONSerialization JSONObjectWithData:URLData options:NSJSONReadingMutableContainers error:nil];

Note that you'll want to verify that the parsed JSON object is indeed an array as expected, and is not/does not contain [NSNull null].

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top