2014-05-12 42 views
0

我從Yummly API獲取數據,我想將它用作序列化的JSON數據。但是,它目前是一個字符串,我不知道如何正確地將其轉換爲數據。該代碼如下:將NSString轉換爲NSData以便在XCODE中使用

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

某處過去四年線,它沒有做它應該並且在數據對象的數據。任何意見或正確的方向快速提示非常感謝!謝謝正在從NSJSONSerialization對象返回you1

+1

你爲什麼要做subdataWithRange?爲什麼你不提供NSError指針給JSONObjectWithData'錯誤:'參數(然後檢查產​​生的錯誤信息)? –

回答

0

看的錯誤,如

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

這可能給你一個什麼樣的錯誤提示。這應該工作,但。 爲什麼你在做URLData = [URLData subdataWithRange:NSMakeRange(0, [URLData length] - 1)];?你不需要複製數據,如果這就是你這樣做的原因。

此外,它似乎像你假設得到一個數組作爲頂級對象(由

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

判斷,但這是一本字典。基本上你可能想要一本字典,而不是數組。這是應該

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

但得到返回的錯誤會告訴你。

0

它看起來像你過於複雜的事情了一下。你不需要在這個數據帶來一個NSString。相反,只需將其作爲NSData並將其交給解析器即可。

嘗試:

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

注意,你要驗證解析的JSON對象確實是一個數組不如預期,而不是/不包含[NSNull null]