I have a use case where I would like to update an objects specific fields given dynamic JSON.
For example:
struct Transmitter {
enabled: bool, // user modifiable (setpoint)
deadband: f64, // user modifiable (setpoint)
alarm: bool, // user modifiable (setpoint)
accum: i32, // non-modifiable by user
}
From a GUI, the user would send a "setpoint" or modification containing only what was changed to the instance. For example, if the user wanted to enable the alarm field, the GUI would send the following as JSON: "{'alarm': true}". Alternatively, if the user enabled the alarm and change the deadband, the following would be sent: "{'alarm': true, 'deadband': 500}".
Is it possible or is there a way to modifiable fields of a struct given only JSON. Possibly a use case in serde?
#[derive(Serialize, Deserialize)]
struct Config { /* ... */ }; // The struct to update – in your case, a Transmitter
use serde_json::Value;
fn amend(config: Config, new_rules: &Value) -> crate::Result<Config> {
let config: Value = serde_json::to_value(&config).unwrap();
let mut config: BTreeMap<String, Value> = serde_json::from_value(config).unwrap();
let new_rules: BTreeMap<String, Value> = serde_json::from_value(new_rules.clone())?;
for (k, v) in new_rules {
config.insert(k, v);
}
let config: Value = serde_json::to_value(&config).unwrap();
Ok(serde_json::from_value(config)?)
}
It's not the fastest way, and I certainly consider it more of a hack than a solution, but hey, it works!
That doesn't look too bad actually...It's not something that will be happening all that often anyways so I'm not too concerned with speed. I'll definitely play around with that method!