2016-11-16 27 views
-1

的Xcode 8.1部署目標的iOS 9.0NSJSONSerialization isValidJSONObject返回從地點搜索終端接收到的數據錯誤

我越來越緊湊的場地對象的數組從Foursquare的地點搜尋端點預期...

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data 

當我檢查使用...的數據對象

if ([NSJSONSerialization isValidJSONObject:data]) 

我得到一個錯誤。

有人能告訴我這裏有什麼問題嗎?

編輯: 下面是完整的,如果塊...(添加類型強制轉換爲數據中,如果塊之後)

id foundationObject; 

NSLog(@"data:- %@",data); 
if ([NSJSONSerialization isValidJSONObject:(id)data]) 
{ 
    foundationObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; 
    NSLog(@"venues foundation object:- %@",foundationObject); 
} 

此前的代碼沒有IF塊。只是......有人

id foundationObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; 

的變化,當我意識到(使用斷點只是上述聲明後),其foundationObject是零,即使數據沒有。

注意:在我三月份發佈iOS 9.x版本的應用程序時,此工作正常。被稱爲Venue Endpoint的版本是否會有所作爲?

回答

1

你在這裏測試的是NSData。爲isValidJSONObject的輸入是不idNSData

+ (BOOL)isValidJSONObject:(id)obj; 

它返回YES如果obj可以轉換爲JSON數據(NSData),否則NO。

另外,根據文件,

An object that may be converted to JSON must have the following properties:

  1. The top level object is an NSArray or NSDictionary.
  2. All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.
  3. All dictionary keys are instances of NSString.
  4. Numbers are not NaN or infinity.

Calling isValidJSONObject: or attempting a conversion are the definitive ways to tell if a given object can be converted to JSON data.

用於轉換NSData到JSONObject的,你可以使用下面的代碼

NSError *error; 
id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error]; 
if (!error) { 
    // successfully done. 
}else { 
    NSLog(@"error: %@", error.localizedDescription) 
} 

請注意,以找出有什麼錯jsonData(NSData)你從服務器接收數據,必須將NSError對象傳入上述代碼中所示的方法。如果將NSData轉換爲jsonObject失敗,您可以根據這一點找出原因。

請看看這個link的詳細信息,在使用NSError對象的Objective-C

+0

打招呼。我編輯了這個問題。請檢查。已經在做你提到的。 – AceN

+1

請檢查我的答案。你沒有做我在答案中提到的。您沒有將'NSError'對象傳遞給該方法。當你這樣做的時候,你會得到錯誤的值,說明出了什麼問題。我會編輯它以給你一個明確的答案,以找出它出錯的地方。 – KrishnaCA

+0

好!現在明白了!愚蠢的錯誤... – AceN

1

您使用了錯誤的方法在這裏isValidJSONObject會告訴你JSON對象(ID)是否將被轉換成JSON數據或不。

由於每doc

Returns a Boolean value that indicates whether a given object can be converted to JSON data. YES if obj can be converted to JSON data, otherwise NO.

如果您要檢查的數據,那麼你應該使用JSONObjectWithData:options:error:,並檢查它是否是零或不是。

編輯

您需要首先你的數據轉換爲NSDictionaryNSArray這樣

NSMutableDictionary * dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error]; 

然後檢查dict是一個有效的兒子還是不喜歡這個

if([NSJSONSerialization isValidJSONObject:dict]){ 
    NSLog(@"dict is a valid JSON"); 
}else{ 
    NSLog(@"dict is not valid JSON"); 
} 
+0

請再次檢查問題。我做了一個編輯。也是這樣做的。但是捕獲JSONObjectWithData返回值的對象仍然爲零。 – AceN

+0

@AceNeerav更新了我的回答 – Rajat

+0

在使用'JSONObjectWithData'轉換數據後檢查'isValidJSONObject'沒有意義。如果數據不代表有效的json對象,那麼'JSONObjectWithData'將返回nil。 – dan