2015-07-21 32 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