是否可以在JSON中使用一个值来确定如何使用serde反序列化JSON的其余部分?例如,考虑以下代码:
use serde::{Serialize, Deserialize};
use serde_repr::*;
#[derive(Serialize_repr, Deserialize_repr, Debug)]
#[repr(u8)]
enum StructType {
Foo = 1,
Bar = 2
}
#[derive(Serialize, Deserialize, Debug)]
struct Foo {
a: String,
b: u8
}
#[derive(Serialize, Deserialize, Debug)]
struct Bar {
x: String,
y: u32,
z: u16
}
#[derive(Serialize, Deserialize, Debug)]
struct AllMyStuff {
type: StructType,
data: //HELP: Not sure what to put here
}
我想要实现的是对数据进行反序列化,即使分多个步骤进行,在
type
中的AllMyStuff
字段也可以确定data
中存在哪种结构数据。例如,给定以下伪代码,我最终希望拥有一个带有适当数据的Bar
结构:data = {"type": "2", "data": { "x": "Hello world", "y": "18", "z": "5" } }
// 1) use serde_json to deserialize a AllMyStuff struct, not erroring on the "data" blob
// 2) Now that we know data is of type "2" (or Bar), parse the remaining "data" into a AllMyStuff struct
如果步骤(1)和(2)可以在单个步骤中完成,那将是很棒的,但不是必需的。我不确定在
data
结构中声明AllMyStuff
的类型是什么类型,也可以启用此类型。
最佳答案
您可以将 serde_json::Value
用作AllMyStuff::data
的类型。它会反序列化任何有效的json对象,并且本身也会实现Deserialize
,因此一旦知道要反序列化的类型(可以通过AllMyStuff::type
),就可以进一步反序列化。尽管这需要更多的间歇性步骤和(通常是临时的)类型,但使您不必手动在Deserialize
上实现enum AllMyStuff { Foo(Foo), Bar(Bar) }
。
关于json - Rust基于json中的枚举反序列化json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60442253/