How can I use serde to deserialize into a hierarchical decentralized configuration? [duplicate]

谁说我不能喝 提交于 2021-02-10 23:26:52

问题


I want to have a JSON config file of the form:

{
    "general_option_foo": true, 
    "general_option_bar": "hello world!", 
    "modules": [
        { "name": "moduleA", "module_options" : {"optFoo":"foo"} }, 
        { "name" : "moduleB", "module_options" : {"optBar":[3,4], "optBuzz": true} }
        { "name": "moduleA", "module_options" : {"optFoo":"bar"} }, 
    ]
}

My application supports many different modules that are each configurable, and which get instantiated how many times and with what options should be determined by the config file.

With serde, everything will work fine if I make one giant struct that contains everything, but I want a more modular design. The creator of each module should be able to define a serializable struct for their module's parameters without having to look at the others. In particular, I am looking to avoid having one big central enum with all modules, I want to use trait based polymorphism instead.

How do I deserialize into trait, not a concrete type? is similar, but all the answers fall back to using a central enum.

I believe what I want is something like:

#[derive(Deserialize)]
struct ModuleConfig {
    name: String,
    module_options: Box<dyn Deserialize>,
}

#[derive(Deserialize)]
struct GeneralOptions {
    general_option_foo: bool,
    general_option_bar: String,
    modules: Vec<ModuleConfig>,
}

I assume serde is going to need some help with using the module name to look up the corresponding trait impl to actually do the deserialization. Is this possible? Is there a good example somewhere I could work from?

来源:https://stackoverflow.com/questions/63253424/how-can-i-use-serde-to-deserialize-into-a-hierarchical-decentralized-configurati

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!