【发布时间】:2020-02-27 21:51:54
【问题描述】:
是否可以使用 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
}
我想要实现的是数据的反序列化,即使在多个步骤中,AllMyStuff 中的type 字段确定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) 能够以某种方式在一个步骤中完成,那就太棒了,但不是必需的。我不确定在 AllMyStuff 结构中声明 data 的类型以启用此功能。
【问题讨论】: