从String中删除单个backSlash

时间:2017-09-24 12:52:22

标签: ios swift string

我尝试将json参数发送到服务器。有我的所有代码,但我有反斜杠字符的问题。 这是包含backSlash字符的测试变量结果。我应该删除此字符,因为在服务器端我输入错误无效,服务器无法检测发送参数。

替换字符后的

测试变量“ “{\” 力\ “:\” 1 \” \ “从\”:\ “0 \”,\ “标志\”:\ “1 \” \ “到\”:\ “0 \”, \ “规范\”:{\ “propValueMask \”:\ “* \”,\ “itemsType \”:\ “avl_resource \”,\ “sortType \”:\ “SYS_NAME \”,\ “propType \”:\ “avl_resource \”,\ “PROPNAME \”:\ “SYS_NAME \”}}“

private func RegisterForGetSourceList() {

    var sid = ""

    if let authEntity = AuthenticationManager.shareInstance.fetchAuthenticationEntity() {

        if let tokenKey = authEntity.sID {
            sid = tokenKey
        }
    }

    let specParam = [
        "itemsType": "avl_resource",
        "propName": "sys_name",
        "propValueMask": "*",
        "sortType": "sys_name",
        "propType": "avl_resource"
    ]

    let paramJSON: [String: Any] = [
        "spec": specParam,
        "force": "1",
        "flag": "1",
        "from": "0",
        "to": "0"
        ]

    do {

        let paramData = try JSONSerialization.data(withJSONObject: paramJSON, options: .prettyPrinted)

        if let paramString = NSString(data: paramData, encoding: String.Encoding.utf8.rawValue) as String? {

            var test = String(paramString.characters.filter { !" \n\t\r".characters.contains($0) })

            test = test.replacingOccurrences(of: "\\", with: "", options: NSString.CompareOptions.literal, range: nil)

            let parameters = [Constant.SVC:Constant.SEARCH_ITEMS_SVC,Constant.SID:sid,Constant.PARAM:test] as [String: Any]

            LibraryAPI.shareInstance.RunHttpPostJSONRequest(parameters: parameters, contentType: "JSON", closure: { success, error in

                if let result = success as? [String: Any] {
                    if let eid = result["eid"] as? String {}
                } else if error != nil  {
                    print(error?.localizedDescription ?? "there was an error in get response")
                }
            })
        }
    } catch {
        print(error.localizedDescription)
    }
}

我读了很多链接,在所有主题中建议替换“\”,但这不起作用。 有人提出了一些解决这个问题的建议  感谢。

1 个答案:

答案 0 :(得分:1)

正如vadian建议的那样,字符串反斜杠是虚拟的,不会发送到服务器。

如果你想打印json进行调试,我推荐这种方法:

var json = try JSONSerialization.jsonObject(with: paramData, options: .allowFragments)

确保将其包裹在do-catch块中。

如果你想把json作为一个字符串,你可以这样做:

let convertedString = String(data: paramData, encoding: .utf8)