gpt4 book ai didi

swift - 对 Swift 中可以和数组或单个元素进行解码的 JSON 数据很热门?

转载 作者:行者123 更新时间:2023-12-04 01:01:02 24 4
gpt4 key购买 nike

我有一个名为 Info 的结构,它根据接收到的数据进行解码。但有时,data 中的一个值可以是 double 型或 double 型数组。如何为此设置我的结构?

struct Info: Decodable {
let author: String
let title: String
let tags: [Tags]
let price: [Double]
enum Tags: String, Decodable {
case nonfiction
case biography
case fiction
}
}

根据 url,我要么得到双倍价格

{
"author" : "Mark A",
"title" : "The Great Deman",
"tags" : [
"nonfiction",
"biography"
],
"price" : "242"

}

或者我把它作为一个 double 数组

{
"author" : "Mark A",
"title" : "The Great Deman",
"tags" : [
"nonfiction",
"biography"
],
"price" : [
"242",
"299",
"335"
]

}

我想设置我的结构,这样如果我收到一个 double 而不是 double 组,价格应该被解码为 1 个 double 组。

最佳答案

您的 JSON 实际上是一个字符串或字符串数​​组。所以你需要创建一个自定义解码器来解码,然后将它们转换为Double:

struct Info {
let author, title: String
let tags: [Tags]
let price: [Double]
enum Tags: String, Codable {
case nonfiction, biography, fiction
}
}

extension Info: Codable {
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
author = try container.decode(String.self, forKey: .author)
title = try container.decode(String.self, forKey: .title)
tags = try container.decode([Tags].self, forKey: .tags)
do {
price = try [Double(container.decode(String.self, forKey: .price)) ?? .zero]
} catch {
price = try container.decode([String].self, forKey: .price).compactMap(Double.init)
}
}
}

Playground 测试

let infoData = Data("""
{
"author" : "Mark A",
"title" : "The Great Deman",
"tags" : [
"nonfiction",
"biography"
],
"price" : "242"

}
""".utf8)
do {
let info = try JSONDecoder().decode(Info.self, from: infoData)
print("price",info.price) // "price [242.0]\n"
} catch {
print(error)
}

let infoData2 = Data("""
{
"author" : "Mark A",
"title" : "The Great Deman",
"tags" : [
"nonfiction",
"biography"
],
"price" : [
"242",
"299",
"335"
]

}
""".utf8)

do {
let info = try JSONDecoder().decode(Info.self, from: infoData2)
print("price",info.price) // "price [242.0, 299.0, 335.0]\n"
} catch {
print(error)
}

关于swift - 对 Swift 中可以和数组或单个元素进行解码的 JSON 数据很热门?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58359549/

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