使用JSON解码Swift 4 Xcode的问题

时间:2018-03-31 09:24:17

标签: xcode swift4 jsondecoder

我在这里有一个问题...我正在使用WooCommerce API从数据库中获取数据...这个代码的一切都很棒,但我有一个奇怪的问题,获取精选照片(featured_src),特色照片价值是一个当产品图像存在时的字符串,但是当产品没有图像时,我得到一个bool值而不是字符串(我得到一个假)。应用程序崩溃了。正如您在我的代码中看到的那样,我将属性指定为String或int或....并且我将featured_src设置为字符串,但有时我得到一个bool值。我该如何编辑我的代码?

docs = []
analyzedDocument = namedtuple('AnalyzedDocument', 'words tags')
for i in range(0,len(train1)):
    words1 = train1[i]
    words2 = train2[i]
    tags1 = [2*i]
    tags2 = [2*i+1]
    docs.append(analyzedDocument(words1, tags1))
    docs.append(analyzedDocument(words2, tags2))

emb="glove.6B.100d.txt"
model = doc2vec.Doc2Vec(docs, vector_size = 300, window = 10, min_count = 1,pretrained_emb=emb)

1 个答案:

答案 0 :(得分:0)

服务器编码非常糟糕。但作为开发人员,我们必须与我们所拥有的一致。您必须手动解码Product。另外,我认为feature_src更接近URL?而非String?(如果需要,可以更改)。

此处的关键点是,如果密钥不包含try decoder.decode(URL.self, ...),而不是使用URL并收到错误,则使用try? decoder.decode(URL.self, ...)并获取nil }。

struct Product: Decodable {
    let title: String
    let id: Int
    let price: String
    let salePrice: String?
    let featuredSource: URL?
    let shortDescription: String

    private enum CodingKeys: String, CodingKey {
        case title, id, price
        case salePrice = "sale_price"
        case featuredSource = "featured_src"
        case shortDescription = "short_description"
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)

        // Nothing special here, just typical manual decoding
        title            = try container.decode(String.self, forKey: .title)
        id               = try container.decode(Int.self, forKey: .id)
        price            = try container.decode(String.self, forKey: .price)
        salePrice        = try container.decodeIfPresent(String.self, forKey: .salePrice)
        shortDescription = try container.decode(String.self, forKey: .shortDescription)

        // Notice that we use try? instead of try
        featuredSource   = try? container.decode(URL.self, forKey: .featuredSource)
    }
}