2015-07-21 72 views
2

我正在向URL发出请求。带有重音/拉丁字符的JSON请求

其中一个团队有拉丁字符Ñ似乎使我的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") 
      } 
     } 

回答

2

JSON是二进制格式,并且没有文本编码的概念(如可通过其开始application/而非text/ mime类型来推断。JSON总是编码为Unicode(UTF-8,UTF-16或UTF-32)很清楚the specification(8.1节)

可能是服务器向你发送了无效的JSON(错误地编码为Latin-1,这可能会使它看起来像解析器中的UTF-8不好) )。然后补救措施将是

  1. 修复服务器。
  2. 如果失败1,你需要某种形式的黑客:
    1. 使用Latin1的字符编码
    2. 转换为使用UTF-8字符编码的NSString NSData的
    3. 解析JSON
  3. 转换的NSData到NSString的
+0

由于名字的性质/的,我们正在处理我们的人等使用ISO-8859-1编码。我正在使用swiftyJSON来解析JSON,有什么办法可以让我简单地改变swiftyJSON使用的编码吗? 这里是源文件:https://raw.githubusercontent.com/SwiftyJSON/SwiftyJSON/master/Source/SwiftyJSON.swift – FredLoh

+0

不需要,UTF-8支持拉丁-1可以表示的所有字符等等。 – Krumelur