【问题标题】:How can I dynamically define the struct for serde_json when the JSON structure is changed without recompiling?当 JSON 结构更改而不重新编译时,如何动态定义 serde_json 的结构?
【发布时间】:2020-12-09 14:59:07
【问题描述】:

例如,我们添加一个在 *.rs 脚本中使用的结构

#[derive(Serialize, Deserialize, Debug)]
struct Foo {
    Output: OUTPUT,
    input: INPUT,
    logs: LOGS,
}

#[derive(Serialize, Deserialize, Debug)]
struct OUTPUT {
    width: u32,
    samplerate: u32,
}

#[derive(Serialize, Deserialize, Debug)]
struct INPUT {
    fileinputuri: String,
}

#[derive(Serialize, Deserialize, Debug)]
struct LOGS {
    statuslog: String,
}

这是被引用的

let var: Foo = serde_json::from_str(&contents).expect("error while reading json");

当我在 JSON 中将字段 width: u32, 更改为 n_width: u32, 时,我们会将结构更改为

#[derive(Serialize, Deserialize, Debug)]
struct OUTPUT {
    n_width: u32,
    samplerate: u32,
}

与其将其添加到 *.rs 文件并每次更新它,是否可以将结构提取到配置文件并在函数调用时更新和加载?

从 *.rs 文件中分离结构是否有任何安全或性能影响?

是否有更好的匿名/未命名方式可以在不需要更新结构的情况下对 JSON 进行更改?

根据下面的评论,使用serde_json::Value 是一种选择,但这是一种可以用来代替强类型结构的安全方法吗?我担心内存安全和防止恶意用户访问 JSON 文件的安全性。

pub enum Value {
    Null,
    Bool(bool),
    Number(Number),
    String(String),
    Array(Vec<Value>),
    Object(Map<String, Value>),
}

假设本程序中不需要进一步引用n_width字段,则Rust开发团队无需打开代码,只有JSON团队对JSON文件和struct文件进行修改.

【问题讨论】:

  • 您应该使用Value 而不是Deserialize
  • @Aplet123 这是一种安全的做法,如果可以使用强类型选项,我注意到许多讨论不鼓励value
  • 动态加载模式时不需要静态类型。也就是说,您仍然可以在 Value 上进行类型验证并拥有强类型,只是在运行时而不是编译时。

标签: rust serde-json


【解决方案1】:

如果您想要动态定义的数据验证,您应该考虑使用 JSON Schema 之类的东西。

如果您需要混合使用动态和静态字段,可以将其与 serde(flatten) 一起使用(如 Shepmaster 的回答中所指出的)。

【讨论】:

    【解决方案2】:

    假设本程序中不需要进一步引用n_width字段,因此Rust开发团队无需打开代码,只有JSON团队对JSON文件和struct文件进行修改.

    如果 Rust 代码不关心字段,那么首先不要将它们添加到结构中。数据中未包含在结构中的其他字段将是 silently ignored by default

    如果您需要捆绑额外数据,但从不需要在 Rust 代码中对其进行操作(例如在代理应用程序中),请查看 How can I use Serde's custom (de)serialization to update a subset of arbitrary input?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多