我有 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
所以根据苹果和我的经验,我认为您的服务器数据库使用苹果不支持的编码选项发送数据。正如我之前所说,您的服务器数据库应该使用 UTF-8。您的数据库表使用其他编码选项。
关于ios - 在序列化 swift 之前编码 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37343145/