0

有人可以帮我吗?我在此示例中使用 Playground,因此您可以将整个代码放入 Playground 并查看结果。

我发现当我删除这一行时:

 "address_format": "{{recipient}}\n{{street}}\n{{postalcode}} {{city}}\n{{country}}",

它似乎工作。

(JSON 已验证)

import UIKit

struct Country : Decodable {

    enum CodingKeys: String, CodingKey {
        case continent
        case alpha2
        case name
    }

    var name : String?
    var continent : String?
    var alpha2 : String?

}

let json = """
[
{
"continent": "Europe",
"alpha2": "AD",
"alpha3": "AND",
"country_code": "376",
"currency": "EUR",
"international_prefix": "00",
"ioc": "AND",
"latitude": "42 30 N",
"longitude": "1 30 E",
"name": "Andorra",
"names": [
"Andorre",
"Andorra",
"アンドラ"],
"translations": {
"en": "Andorre",
"it": "Andorra",
"de": "Andorra",
"fr": "Andorre",
"es": null,
"ja": "アンドラ",
"nl": "Andorra",
"ru": "Андорра"},
"national_destination_code_lengths": [2],
"national_number_lengths": [6,7,8,9],
"national_prefix": "None",
"number": "020",
"region": "Europe",
"subregion": "Southern Europe",
"un_locode": "AD",
"languages": ["ca"],
"nationality": "Andorran"},
{
"continent": "Asia",
"address_format": "{{recipient}}\n{{street}}\n{{postalcode}} {{city}}\n{{country}}",
"alpha2": "AE",
"alpha3": "ARE",
"country_code": "971",
"currency": "AED",
"international_prefix": "00",
"ioc": "UAE",
"latitude": "24 00 N",
"longitude": "54 00 E",
"name": "United Arab Emirates",
"names": [
"United Arab Emirates",
"Vereinigte Arabische Emirate",
"Émirats Arabes Unis",
"Emiratos Árabes Unidos",
"アラブ首長国連邦",
"Verenigde Arabische Emiraten"],
"translations": {
"en": "United Arab Emirates",
"it": "Emirati Arabi Uniti",
"de": "Vereinigte Arabische Emirate",
"fr": "Émirats Arabes Unis",
"es": "Emiratos Árabes Unidos",
"ja": "アラブ首長国連邦",
"nl": "Verenigde Arabische Emiraten",
"ru": "Объединенные Арабские Эмираты"},
"national_destination_code_lengths": [2],
"national_number_lengths": [7,8,9],
"national_prefix": "0",
"number": "784",
"region": "Asia",
"subregion": "Western Asia",
"un_locode": "AE",
"languages": ["ar"],
"nationality": "Emirian"}
]
""".data(using: .utf8)!

let decoder = JSONDecoder()
do {
    let countries = try decoder.decode([Country].self, from: json)
    print(countries)

} catch {
    print("erro")
}
4

1 回答 1

1

如果您要打印实际的错误信息

“字符 722 周围未转义的控制字符。”

而不是无意义的文字字符串"erro" ,解决方案是显而易见的:

换行符\n必须转义:

"address_format": "{{recipient}}\\n{{street}}\\n{{postalcode}} {{city}}\\n{{country}}",

你可以解决这个问题

let json = """
[
...
]
""".replacingOccurrences(of: "}\n{", with: "}\\n{").data(using: .utf8)!
于 2017-07-10T06:41:10.523 回答