2013-11-26 48 views
0

我已經JSON解析在Xcode中,像這樣:試圖在Xcode NSCocoaErrorDomain代碼來解析JSON = 3840

-(void)getCheckUserData:(NSData *)data { 

NSError *error; 
if (!error) { 

checkUserJSON = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 
} 
else{ 
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Uh Oh" message:@"Spaghetti-O" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; 
    [alert show]; 
} 


} 

-(void) startCheckingUserLogin { 

NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:kCheck_user] 
              cachePolicy:NSURLRequestUseProtocolCachePolicy 
             timeoutInterval:20.0]; 

NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest 
                   delegate:self]; 
if (theConnection) { 
    NSURL *url = [NSURL URLWithString:kCheck_user]; 
    NSData *data = [NSData dataWithContentsOfURL:url]; 
    [self getCheckUserData:data]; 
} 

} 

但是我僱了一名Web開發人員,他更新了從phpMyAdmin的數據了我的過時的PHP文件和用JSON編碼它。現在我在xcode中得到NSCocoaErrorDomain Code = 3840消息。

這裏是php文件我抓住從數據:

<?php 

require_once('classes/secure.php'); 
$SECURE = new Secure(); 

if(!isset($_POST[ 'var1' ])) { exit("ERROR: no var1"); } 
if(!isset($_POST[ 'var2' ])) { exit("ERROR: no var2"); } 

$VARONE = $_POST[ 'var1' ]; 
$VARTWO = $_POST[ 'var2' ]; 

$RESULT = $SECURE->checkPassword($VARONE, $VARTWO); // Check VARONE/VARTWO 
unset($SECURE); // Unset Secure 
exit(json_encode($RESULT)); // Return result as JSON string 

?> 

我需要做什麼改變嗎?

+0

您可以手動執行對Web服務的請求(即不通過應用程序)並編輯您的文章以包含結果嗎?換句話說,你確定你的json是合法的嗎? –

回答

3

問題是編碼。我有一個Web服務可以在99%的時間內正常工作,但對具有某些參數的一個端點的響應失敗。我在RESTClient中運行了請求,並在頭部注意到響應是ISO-8859-1,又名Latin-1。

訣竅是將Latin-1數據轉換爲NSString,然後使用NSString將其轉換回UTF8數據以使NSJSONSerialization變得快樂。

NSError *error; 
NSArray *json = [NSJSONSerialization JSONObjectWithData:self->receivedData options:0 error:&error]; 
if (!json && error && [error.domain isEqualToString:NSCocoaErrorDomain] && (error.code == NSPropertyListReadCorruptError)) { 
    // Encoding issue, try Latin-1 
    NSString *jsonString = [[NSString alloc] initWithData:self->receivedData encoding:NSISOLatin1StringEncoding]; 
    if (jsonString) { 
     // Need to re-encode as UTF8 to parse, thanks Apple 
     json = [NSJSONSerialization JSONObjectWithData: 
       [jsonString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES] 
      options:0 error:&error]; 
    } 
} 

我確定有很多很棒的REST工具,你可能想檢查一些。 RESTClient是Firefox的一個插件。

+0

只是說:如果服務器在ISO-8859-1中發送了應該是JSON的內容,那麼它是無效的JSON,並且服務器已損壞。 JSON是UTF-8,或UTF-16或UTF-32。沒有其他的。 – gnasher729

相關問題