我用这个代码从互联网上获取一些json
数据
facilitiesService.facilitiesServerDataJson(urlToFetch: url_, jsoncompleted: { () in
let responseData: Data = self.facilitiesService.UpdateJsonString.data(using: String.Encoding.utf8)!
let decoder = JSONDecoder()
let facilityDataListTmp = try decoder.decode([FacilityData].self, from: responseData)
可以很好地用于字母,但是我的json
也包含日语文本,所以我的输出变成这样
nicopass.FacilityData(
tn_newsid: 999900001,
tn_midashi: "æºæã®å¤ã«ç¾ããç¥ç§ã®è¹ãã ã¼ã³ãã¦ããè¦ãã幸éã訪ããï¼è½å·®55mã§åå£æãã®ç¾ãã絶æ¯ãæããåç"
正如你所看到的,它可以很好地用于字母表,但是日语变成了一些奇怪的字符。我可以在这里解码从utf-8
到正常文本>>link
但是我想知道如何在源代码中解码它。
我认为这里的问题是你正在转换字符串与UTF8:
let responseData: Data = self.facilitiesService.UpdateJsonString.data(using: String.Encoding.utf8)!
我创建了一个playground文件来测试日语和法语字母的编码/解码,它可以正常工作。
import UIKit
// the text you want to encode/decode
let myChars = "星空観察に最適なロケーション. Also other chars. Même du Français écrit par un Brésilien."
// your json node represented as a Struct
struct MyContent: Codable {
let id: Int
let content: String
}
// your data
let myContent = MyContent(id: 1, content: myChars)
do {
// we encode the content, the encoded variable here would be the data you would get from your webservice.
let encoded = try JSONEncoder().encode(myContent)
// we decode your data without using any encoding type
let val = try JSONDecoder().decode(MyContent.self, from: encoded)
// the content printed is correctly presented.
print(val.content)
} catch {
// should not get any error, but just in case.
print("Error: (error.localizedDescription)")
}
// version using a String as a starting point
let jsonString = """
{
"id": 1,
"content": "(myChars)"
}
"""
print(jsonString)
if let data = jsonString.data(using: .utf8) {
do {
// we decode your data without using any encoding type
let val = try JSONDecoder().decode(MyContent.self, from: data)
// the content printed is correctly presented.
print(val.content)
} catch {
// should not get any error, but just in case.
print("Error: (error)")
}
}
我更新了操场,这样你可以更好地看到所有这些转换。
审查你发布的代码位,我看到你有这个self.facilitiesService.UpdateJsonString它是一个字符串,通常当我们做一个web服务请求时我们得到的结果是Data,所以我会说数据已经被解码了。我建议你检查一下是怎么做的。可能已经有类似String(data: data, encoding: .utf8)的东西,也许您应该将这个UpdateJsonString变量修改为data而不是String。这样就避免了一次操作。
我希望这对你有帮助!:)