Krutarth Patel Krutarth Patel - 4 months ago 74
Swift Question

How to remove \n from string in swift?

Here is my string and i want to remove some characters from string.My code is below

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


and i want to convert into this format.

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


How to remove \ from string to make JSON string proper?
Please help me.

Answer

This is json in String response if you want to get dictionary from that try this, Here str is your string

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)
}