1

Unit structs don't have a value, however serde is unable to parse them from missing values. I have to explicitly set the value to null. For example:

use serde::Deserialize;
use serde_json::json;

#[derive(Deserialize)]
pub struct SomeStruct;

#[derive(Deserialize)]
#[serde(tag = "type", content = "config")]
pub enum Value {
    Fixed(String),
    FromMatch { foo: String, bar: SomeStruct },
}

fn main() {
    let config_json = json!({
        "type": "FromMatch",
        "config": {
            "foo": "foo",
        }
    });

    let _config: Value = serde_json::from_value(config_json).unwrap();
}

If I run the above I get the following error: "missing field 'bar'", even though bar doesn't need a value. However if I change the json to:

let config_json = json!({
    "type": "FromMatch",
    "config": {
        "foo": "foo",
        "bar": null
    }
});

This runs fine. Is there someway I can parse missing values into unit structs correctly?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
user3690467
  • 3,049
  • 6
  • 27
  • 54

1 Answers1

0

Derive or implement Default for your structure and then mark the field with #[serde(skip)].

Colonel Thirty Two
  • 23,953
  • 8
  • 45
  • 85