gpt4 book ai didi

json - Rust Serde-是否可以将可能处于两种不同布局的json数据映射回单个结构?

转载 作者:行者123 更新时间:2023-12-03 11:28:19 26 4
gpt4 key购买 nike

我尝试映射到我的结构的数据有两种格式:

使用card_faces,当卡片上有一张以上的面孔时:

{
"object": "card",
"id": "some_id",
"lang": "en",
"released_at": "2012-02-03",
"card_faces": [
{
"name": "some_name",
"cost": "5",
"ctype": "some_type",
"colors": [
"R",
"B"
]
},
{
"name": "another_name",
"cost": "",
"ctype": "another_type",
"colors": [
"R",
"B"
]
}
],
"set_code": "some_code"
}

如果没有 card_faces,则只有一张脸时(脸部字段仅放置在根中):
{
"object": "card",
"id": "some_id",
"lang": "en",
"released_at": "2012-02-03",
"name": "some_name",
"cost": "5",
"ctype": "some_type",
"colors": [
"R",
"B"
],
"set_code": "some_code"
}

我希望我的结构始终有一个 Vec<CardFace>字段。就像是:
#[derive(Deserialize)]
struct Card {
object: String,
id: String,
lang: String,
released_at: String,
faces: Vec<CardFace>,
set_code: String,
}

是否可以反序列化这些对象并将面部字段强制转换为所需的格式,或者在反序列化之前我需要操纵json吗?

最佳答案

我会使用中介enum来做到这一点:

#[derive(Deserialize)]
#[serde(untagged)]
enum CardTmpDeser {
Card {
object: String,
id: String,
lang: String,
released_at: String,
card_faces: Vec<CardFace>,
set_code: String,
},
SingleCard {
object: String,
id: String,
lang: String,
released_at: String,
name: String,
cost: String,
ctype: String,
colors: Vec<String>,
set_code: String,
},
}

使用 #[serde(untagged)]属性,您可以透明地反序列化您拥有的两种数据。

现在,只需使用 #[serde(from = "CardTmpDeser")]标记您的实际结构即可:

#[derive(Debug, Deserialize)]
#[serde(from = "CardTmpDeser")]
pub struct Card {
object: String,
id: String,
lang: String,
released_at: String,
card_faces: Vec<CardFace>,
set_code: String,
}

并为 From<CardTmpDeser>实现 Card,您就可以开始了! serde将使用 CardTmpDeser自动反序列化您的数据,但会透明地将其转换为您的最终类型。

( Permalink to the playground with full working example)

关于json - Rust Serde-是否可以将可能处于两种不同布局的json数据映射回单个结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60877381/

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