2012-05-07 74 views
1

傳遞JSON數據我有此方法 -用希伯來語值問題(?UTF8)

NSArray *objects = [NSArray arrayWithObjects:appDelegate.UserID,itemName.text,@"1",@"1",itemDegem.text,itemDescription.text, nil]; 
NSArray *keys = [NSArray arrayWithObjects:@"userId",@"itemName",@"itemCategoryId",@"regionId",@"degemName",@"itemDescription", nil]; 

NSDictionary *registerDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys]; 
NSString *jsonRequest = [registerDict JSONRepresentation];  
NSLog(@"jsonRequest is %@", jsonRequest); 

NSURL *url = [NSURL URLWithString:@"http://www.somedomain.com/method"]; 

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; 

NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]]; 

[request setHTTPMethod:@"POST"]; 
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; 
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"]; 
[request setHTTPBody: requestData]; 

NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self]; 
if (connection) { 
    self.responseData = [NSMutableData data]; 
} 

,但是當我在我的對象發送字符串不是英文IM從服務器獲取錯誤。 現在,我知道它是一個UTF8問題,但我確實將它設置爲UTF8。有人能幫我弄明白嗎?

+2

什麼是你從服務器得到的錯誤?你怎麼知道UTF-8是問題所在? – bdesham

+0

即時通訊獲得一些基本上說html代碼:服務器遇到錯誤處理請求。異常消息是'格式化程序在嘗試反序列化消息時拋出異常:嘗試反序列化參數http://tempuri.org/:itemDescription時出現錯誤。 InnerException消息是'反序列化System.String類型的對象時發生錯誤。意外的文件結束。以下元素未關閉:itemDescription,root。'。請參閱InnerException獲取更多細節。'。請參閱服務器日誌的詳細信息請參見 –

回答

4

我認爲錯誤是strlen([jsonRequest UTF8String])不等於[jsonRequest length]

使用NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];使用UTF8編碼一個的NSString轉換爲NSData的。

+0

:如何將NSString的值轉換爲NSData的?](http://stackoverflow.com/questions/901357/how-do-i-convert-a-nsstring-value-to- NSData的) –