iddm / serde-aux

An auxiliary serde library providing helpful functions for serialisation and deserialisation for containers, struct fields and others.
MIT License
152 stars 26 forks source link

"deserialize_option_number_from_string" fails when property does not exist. #42

Closed physics515 closed 5 months ago

physics515 commented 5 months ago

I have a JSON object

{
    "property1": "intString",
    "property2": "intString",
    "sometimesProperty": "intString",
}

and a rust struct link this:

use serde_aux::prelude::*;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub struct Object {
    #[serde(deserialize_with = "deserialize_number_from_string")]
    property1: u64,

    #[serde(deserialize_with = "deserialize_number_from_string")]
    property2: u64,

    #[serde(rename = "sometimesProperty", deserialize_with = "deserialize_option_number_from_string")]
    sometimes_property: Option<u64>,
}

This works as long as sometimesProperty exists on the json but if it doesn't then I get a Serde error saying that it expected sometimesProperty.

Is this expected behavior?

physics515 commented 5 months ago

Nevermind, I fount the answer elsewhere in the docs.

You have to include serde default for it to fallback.

use serde_aux::prelude::*;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub struct Object {
    #[serde(deserialize_with = "deserialize_number_from_string")]
    property1: u64,

    #[serde(deserialize_with = "deserialize_number_from_string")]
    property2: u64,

    #[serde(default, rename = "sometimesProperty", deserialize_with = "deserialize_option_number_from_string")]
    sometimes_property: Option<u64>,
}