gpt4 book ai didi

ios - Codable/Decodable 不解码

转载 作者:行者123 更新时间:2023-11-28 15:27:52 25 4
gpt4 key购买 nike

有人可以帮我吗?我在此示例中使用了 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")
}

最佳答案

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

"Unescaped control character around character 722."

而不是无意义的文字字符串“erro”解决方案很明显:

换行符 \n 必须转义:

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

你可以用

解决这个问题
let json = """
[
...
]
""".replacingOccurrences(of: "}\n{", with: "}\\n{").data(using: .utf8)!

关于ios - Codable/Decodable 不解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45004659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com