-
-
Notifications
You must be signed in to change notification settings - Fork 786
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Ability to use default value even if set to null #1098
Comments
I am open to supporting this better. For now the current workaround would be a use serde::{Deserialize, Deserializer};
#[derive(Serialize, Deserialize, Debug)]
struct Request {
#[serde(default = "Priority::lowest", deserialize_with = "nullable_priority")]
priority: Priority,
}
fn nullable_priority<'de, D>(deserializer: D) -> Result<Priority, D::Error>
where D: Deserializer<'de>
{
let opt = Option::deserialize(deserializer)?;
Ok(opt.unwrap_or_else(Priority::lowest))
} |
@dtolnay oh thanks. That's nice and small compared to the monster that I wrote :)... |
A |
Hi! Thank you for an awesome serde :) Sorry for writing to an old thread, just wanted to know why there's a need for a separate attribute? Couldn't If I understand correctly, in the case of JSON deserializing
Here's an example code Is that an expected behaviour, or an inconsistency of Thanks in advance! |
Since, search results land to this page - Here's something that can use 'default' // Omitting other derives, for brevity
#[derive(Deserialize)]
struct Foo {
#[serde(deserialize_with = "deserialize_null_default")]
value: String,
}
fn deserialize_null_default<'de, D, T>(deserializer: D) -> Result<T, D::Error>
where
T: Default + Deserialize<'de>,
D: Deserializer<'de>,
{
let opt = Option::deserialize(deserializer)?;
Ok(opt.unwrap_or_default())
} [playground link] (https://play.integer32.com/?version=stable&mode=debug&edition=2018&gist=d1b67fae798e958b377c622fd009de14) |
serde doesn't set the default for a field which is present and set to null.[1] So we're using a custom deserializer. Fixes #33 [1]: serde-rs/serde#1098
It is an expected behaviour. The default value is used when the variable is not specified. So, null -> default cases are a specific thing, and should be specifically determined. |
Great solution! But need to remember that |
default does not treat a field being set to
null
equal to the field being emitted. More concretely, the following code will panic in the line where it attempts to deserializerequest_c
:The data I want to process sometimes has its field set, sometimes it is set to
null
, and sometimes it is omitted. I want to set a default for when it is null or omitted.This doesn't need to be the default behaviour but having sth like
#[serde(default_on_null)]
would be really nice :). Thanks to @oli-obk suggesting that on IRC.The text was updated successfully, but these errors were encountered: