2016-07-13 36 views
-4

這是我的字符串,我想從字符串中刪除一些字符。我的代碼是低於如何從Swift中的字符串中刪除 n?

"{ \"userpass\" : \"\", \"apikey\" : \"=\", \"deviceid\" : \"\", \"username\" : \"\"}" 

我想轉換成這種格式。

{ 
    "userpass" : "", 
    "username" : "", 
    "deviceid" : "", 
    "apikey" : "=" 
} 

如何從字符串中刪除\以使JSON字符串正確?

+2

你想刪除'\ n'或'\\' –

+0

請檢查我更新的問題 –

+4

這個字符串是漂亮的JSON。您應該**不**嘗試通過執行字符替換/解析來解碼它,但是通過使用適當的JSON方法來解碼它。 – Moritz

回答

1

這是字符串響應json如果你想獲得字典從試試這個,這str是你的字符串

let str = "{ \"userpass\" : \"\", \"apikey\" : \"=\", \"deviceid\" : \"\", \"username\" : \"\"}" 
let data = str.dataUsingEncoding(NSUTF8StringEncoding) 
do { 
    let dic = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSDictionary 
    print(dic) 
} 
catch let e as NSError { 
    print(e.localizedDescription) 
} 
+0

Hi Nirav。 要求是我必須傳遞字典而不是數組作爲參數到服務器。 如何做到這一點,你可以解釋一下嗎? –

+0

檢查我編輯的答案。你會得到字典。 –

+0

是的,我得到dictionary.now問題是如何使用alamofire將它傳遞給服務器? –

-1

在Objective-C

的NSString * stringWithoutSpaces = [yourString stringByReplacingOccurrencesOfString:@ 「 」withString:@「」];

-1
All special characters with in string must use extra \ (escape sequence) to recognize the actual value  

[string stringByReplacingOccurrencesOfString:@"\\n" withString:@""]; 
    or string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) 

hope you will be clear 
+0

[string stringByReplacingOccurrencesOfString:@「\\ n」withString:@「」]; – Nattudurai

+0

你仍然面臨同樣的問題? [string stringByReplacingOccurrencesOfString:@「\\ n」withString:@「」] – Nattudurai

+0

雖然此代碼可能回答問題,但提供有關如何和/或爲何解決問題的其他上下文將提高​​答案的長期價值。 – HiDeo

0

如果您在調試監控po myString看到這將是{ "userpass" : "", "apikey" : "=", "deviceid" : "", "username" : ""},這斜線只是在代碼不在程序

相關問題