I want to deserialize a string of JSON data into a struct with multiple fields and return an error if the ordering of the serialized data does not match the order of the fields in the struct.
I have read through the serde documentation, including the section on custom serialization, but cannot find a solution. I imagine it might be possible to enforce strict ordering by implementing Deserializer with field name checks but I'm not entirely sure about this.
An example following the format of the serde_json docs:
#[derive(Serialize, Deserialize)]
struct Person {
name: String,
age: u8,
phones: Vec<String>,
}
let correct_order = r#"
{
"name": "John Doe",
"age": 43,
"phones": [
"+44 1234567",
"+44 2345678"
]
}"#;
// this deserializes correctly (no error)
let p: Person = serde_json::from_str(data)?;
let incorrect_order = r#"
{
"age": 43,
"phones": [
"+44 1234567",
"+44 2345678"
]
"name": "John Doe"
}"#;
// how to ensure this returns an error? (data fields out of order)
let p2: Person = serde_json::from_str(data)?;