【问题标题】:JSON request with accents/latin characters带有重音/拉丁字符的 JSON 请求
【发布时间】:2026-01-27 16:20:03
【问题描述】:

我目前正在向 URL 发出请求。

其中一个团队的拉丁字符 Ñ 似乎使我的 JSON 为零,因此在我将数据导出到的表中没有显示任何数据。我做了一些研究,我认为我需要将其编码为 NSISOLatin1StringEncoding。

我正在使用 SwiftyJSON 来解析 JSON。

let cuartoURL = NSURL(string: cuartoURLString)

    //initializes request
    let request = NSURLRequest(URL: cuartoURL!)
    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.currentQueue()) { response, jsonDataRequest4, error in
        if jsonDataRequest4 != nil {

        let dataRequest4 = jsonDataRequest4
        //println(NSString(data:dataRequest4, encoding: NSUTF8StringEncoding))

        //takes data, saves it as json
        let cuartoJSON = JSON(data: jsonDataRequest4)

        //checks to see that contents != nil, meaning the JSON file was found
        if cuartoJSON != nil {
            equiposList.removeAll(keepCapacity: false)
            //counts number of teams
            numeroDeEquipos = cuartoJSON["lista-equipos"].count
            println(numeroDeEquipos)

            //saves each variable and appends to a array
            for var index = 0; index < numeroDeEquipos;++index {
                var equipoID = Int(cuartoJSON["lista-equipos"][index]["EquipoID"].number!)
                var nomEquipo = cuartoJSON["lista-equipos"][index]["nomEquipo"].string
                var nomGrupo = cuartoJSON["lista-equipos"][index]["nomGrupo"].string

                var equiposNuevo = listaEquipos(equipoID: equipoID, nomEquipo: nomEquipo!, nomGrupo: nomGrupo!)
                equiposList.append(equiposNuevo)
                self.tableView.reloadData()
            }
            //loadingActivity.hideLoadingActivity(success: true, animated: false)
            //reloads data once json is complete
            self.tableView.reloadData()
        } else {
            //loadingActivity.hideLoadingActivity(success: false, animated: true)
            println("NIL JSON")
            }
        }

【问题讨论】:

    标签: json swift swifty-json


    【解决方案1】:

    JSON 是一种二进制格式,没有文本编码的概念(可以通过它的 mime 类型推断出来,以 application/ 而不是 text/ 开头。JSON 始终编码为 Unicode(UTF-8、UTF-16 或the specification(第 8.1 节)非常清楚地说明了 UTF-32)。

    可能是服务器向您发送了无效的 JSON(错误地编码为 Latin-1,这可能会使解析器看起来像错误的 UTF-8)。那么补救措施就是

    1. 修复服务器。
    2. 如果 1. 失败,您需要一些技巧:
      1. 使用 Latin1 字符编码将 NSData 转换为 NSString
      2. 使用 UTF-8 字符编码将 NSString 转换为 NSData
      3. 解析 JSON

    【讨论】:

    • 由于我们正在处理的人的姓名/等的性质,我们使用 ISO-8859-1 作为编码。我正在使用 swiftyJSON 来解析 JSON,有什么方法可以让我简单地更改 swiftyJSON 使用的编码?这是源文件:raw.githubusercontent.com/SwiftyJSON/SwiftyJSON/master/Source/…
    • 不需要,UTF-8 支持 Latin-1 可以表示的所有字符等等。
    【解决方案2】:

    这对我有用:

    xhr.overrideMimeType("application/json;charset=iso-8859-1");
    

    来自: Fetch json with non ASCI characters like ü, chrome displays network displays correctly

    【讨论】:

      最近更新 更多