2013-10-29 33 views
23

如何防止NSJSONSerialization向我的URL字符串添加額外的反斜槓?如何防止NSJSONSerialization在URL中添加額外的轉義

NSDictionary *info = @{@"myURL":@"http://www.example.com/test"}; 
NSData data = [NSJSONSerialization dataWithJSONObject:info options:0 error:NULL]; 
NSString *string = [[NSString alloc] initWithData:policyData encoding:NSUTF8StringEncoding]; 
NSLog(@"%@", string);//{"myURL":"http:\/\/www.example.com\/test"} 

我可以去除反斜線和使用字符串,但我想跳過這一步,如果可能的...

+0

你找到了解決辦法嗎? –

+1

如果有人在調試器中看到這個,它可能不是你認爲的那樣。 在顯示和打印字符串時,lldb會在字符串中隱藏某些字符。測試,而不是做'po '做'po打印()'。 我的生活中有3個小時因爲這種怪事而失去。 「\」實際上並不存在...... – BTRUE

+0

@BTRUE ......先生,你是一個鋼鐵般的導彈人。你剛剛救了我3個小時。非常感謝。 –

回答

4

啊,這是相當刺激性更應如此,因爲它似乎沒有「快「固定到這個(即,對於NSJSONSerialization)

源:
http://www.blogosfera.co.uk/2013/04/nsjsonserialization-serialization-of-a-string-containing-forward-slashes-and-html-is-escaped-incorrectly/

NSJSONSerialization serialization of a string containing forward slashes/and HTML is escaped incorrectly


(在黑暗中拍攝剛剛在這裏如此忍受我)
如果你是在做你自己的JSON然後簡單地使一個NSData對象進行字符串,並將其發送到服務器。
無需通過NSJSONSerialization。

喜歡的東西:

NSString *strPolicy = [info description]; 
NSData *policyData = [strPolicy dataUsingEncoding:NSUTF8StringEncoding]; 

我知道這不會是這麼簡單,但...唔...反正

+0

感謝您的鏈接。至於在黑暗中拍攝,我會這樣做,如果我手動構建json字符串,但我使用NSJSONSerialization使構建字符串更容易。以上只是這個問題的一個簡單例子。 – joels

+0

是的,有更多的變量和參數要考慮,我可以理解NSJSONSerialization更容易。無論如何,如果我找到解決辦法,我會記得回到這裏。 – staticVoidMan

18

這爲我工作

NSDictionary *policy = ....; 
NSData *policyData = [NSJSONSerialization dataWithJSONObject:policy options:kNilOptions error:&error]; 
if(!policyData && error){ 
    NSLog(@"Error creating JSON: %@", [error localizedDescription]); 
    return; 
} 

//NSJSONSerialization converts a URL string from http://... to http:\/\/... remove the extra escapes 
policyStr = [[NSString alloc] initWithData:policyData encoding:NSUTF8StringEncoding]; 
policyStr = [policyStr stringByReplacingOccurrencesOfString:@"\\/" withString:@"/"]; 
policyData = [policyStr dataUsingEncoding:NSUTF8StringEncoding]; 
+0

這會損壞字符串,如\/\/smileys。 「這是反斜槓後跟斜槓:\\ /」將被替換爲「這是一個反斜槓後跟\ /」,這不是任何人都想要的。 –

+3

@LevWalkin「\/\ /」微笑將被編碼爲「\\/\\ /」,將「\ /」替換爲「/」後將再次爲「\ \ \// /」 –

相關問題