ios - 在序列化 swift 之前编码 JSON

标签 ios json swift encoding

我有 JSON 方法并且在 UTF8 网络服务上工作得很好,但现在有一个带有另一种编码的 JSON,例如 ú =\u00da。我知道我必须编码为 UTF8 才能在 swift 上处理我的 JSON。但我不知道怎么办。在 request.HTTPBody 上有一个 .dataUsingEncoding,这还不够吗?

request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
            data, response, error in
            if error != nil
            {
                print("error=\(error)")
                return
            }

            do{
                let myJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)

                let jsonEmpresas = myJSON["TablaEmp"]!!["item"]
                let empresas: [[String: AnyObject]]

                if let multipleEmpresas = jsonEmpresas as? [[String: AnyObject]] {
                    empresas = multipleEmpresas
                } else if let singleEmpresa = jsonEmpresas as? [String: AnyObject] {
                    empresas = [singleEmpresa]
                } else {
                    empresas = []
                }

                for empresa in empresas{
                    let zcif = empresa["Zcif"] as? String

我在 Do 之前有 let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding),但没有使用

错误:“Error Domain=NSCocoaErrorDomain Code=3840 “字符 0 周围的值无效。”UserInfo={NSDebugDescription=字符 0 周围的值无效。} "

最佳答案

如果您想发送表情符号或其他 Unicode 字符作为参数,您需要对 HTTP 请求进行编码,如 postString.dataUsingEncoding(NSUTF8StringEncoding)!。但是正如您在评论中所说的那样,此网络服务将仅发送字符串或 Int 所以可以使用 postString.dataUsingEncoding(NSASCIIStringEncoding)!。因为该行只影响发送参数,它只对发送参数进行编码,而不对接收的 JSON 值进行解码。所以基本上只取 JSON 值。

所以基本上当你返回一个编码值苹果支持那些编码文本

The data must be in one of the 5 supported encodings listed in the JSON specification: UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE. The data may or may not have a BOM. The most efficient encoding to use for parsing is UTF-8, so if you have a choice in encoding the data passed to this method, use UTF-8

https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSJSONSerialization_Class/#//apple_ref/occ/clm/NSJSONSerialization/JSONObjectWithData:options:error :

所以根据苹果和我的经验,我认为您的服务器数据库使用苹果不支持的编码选项发送数据。正如我之前所说,您的服务器数据库应该使用 UTF-8。您的数据库表使用其他编码选项。

关于ios - 在序列化 swift 之前编码 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37343145/

相关文章:

ios - UISegue中途定位UIView

iOS 13 iPhone 10 和 11 只显示黑色 View 但期待 UITabBarController [ View 层次结构显示它没有高度]

html - Apple iphone 导致按钮在网站上被压扁

objective-c - 将 UI Picker 添加到 UITextView

javascript - 如何在 C# 中将 json 值转换为字典并使用字符串值来寻址它们?

vb.net - JSON.Net VB 反序列化不起作用

python - 我怎样才能优化这个Python代码的时间

ios - 通过 Xcode 中的 AVAudioPlayer 从后台任务开始播放音频

ios - 如何使 TableView 一次加载所有数据并且在滚动时不更改所述数据?

swift - 如何从 scenekit 场景中删除所有节点?