如果值为 ,我想跳过字段序列化false。
在 JSON 中,这将序列化为Foo或。{bar: true}{}
#[derive(Serialize)]
pub struct Foo {
// This does not compile - bool::is_false does not exist
#[serde(skip_serializing_if = "bool::is_false")]
pub bar: bool,
}
Run Code Online (Sandbox Code Playgroud)
好吧,根据 serde 文档:
#[serde(skip_serializing_if = "path")]
调用函数来确定是否跳过序列化该字段。给定的函数必须可调用为fn(&T) -> bool,尽管它可能是通用的T
所以你可以自己定义这样的函数
fn is_false(b: &bool) -> bool { !b }
Run Code Online (Sandbox Code Playgroud)
或者您可以在标准库中查找这样的函数。
Clone::clonestd::ops::Not::not( Playground )bool::not不起作用,因为您需要Notimpl on
&bool:<&bool as std::ops::Not>::not| 归档时间: |
|
| 查看次数: |
3864 次 |
| 最近记录: |