I'm trying to store the value of a field in a global context, but this doesn't work when the JSON object is in the wrong order.
How can I make it so the output is always, a
then b
?
use serde::{Deserialize, Deserializer};
use std::error::Error;
fn a_deserialize<'de, D>(deserializer: D) -> Result<u32, D::Error>
where
D: Deserializer<'de>,
{
let num = Deserialize::deserialize(deserializer)?;
println!("a");
Ok(num)
}
fn b_deserialize<'de, D>(deserializer: D) -> Result<u32, D::Error>
where
D: Deserializer<'de>,
{
let num = Deserialize::deserialize(deserializer)?;
println!("b");
Ok(num)
}
#[derive(Deserialize)]
struct Test {
#[serde(deserialize_with = "a_deserialize")]
a: u32,
#[serde(deserialize_with = "b_deserialize")]
b: u32,
}
fn main() -> Result<(), Box<dyn Error>> {
// notice the order is b then a
let str = "{ \"b\": 1, \"a\": 2 }";
let test: Test = serde_json::from_str(&str)?;
// it prints out b then a, but I want a then b -- the same as in the struct definition
Ok(())
}