Serde json 值省略 None 上的属性

EZ-*_*Z-C 6 rust serde

给定以下 JsonValue:

let mut schema = json!({
    "level": "strict",
    "rule": {}
});
Run Code Online (Sandbox Code Playgroud)

我们将动态地将值插入到此 JsonValue 中

let value: json!({
    "type": property.r#type,
    "minLength": property.min_length,
    "maxLength": property.max_length,
    "enum": property.r#enum
});

schema["rule"]
    .as_object_mut()
    .unwrap()
    .insert(
        String::from(property.name), 
        value
    );

// Struct for Property
#[derive(Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SchemaDocumentProperty
{
    pub name: String,
    pub r#type: Option<String>,
    pub min_length: Option<u32>,
    pub max_length: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub r#enum: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub items: Option<SchemaDocumentPropertyArray>
}
Run Code Online (Sandbox Code Playgroud)

当前输出如下,其中minLengthmaxLengthenum均为 None:

{
    "type": "string",
    "minLength": null,
    "maxLength": null,
    "enum": null
}
Run Code Online (Sandbox Code Playgroud)

我想要的输出:

{
    "type": "string"
}
Run Code Online (Sandbox Code Playgroud)

我想省略 JsonValue 宏中的所有 None 值。

Net*_*ave 5

只需创建一个Value结构体而不是使用json!宏:

#[derive(Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Value
{
    #[serde(skip_serializing_if = "Option::is_none")]
    pub r#type: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_length: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_length: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub r#enum: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub items: Option<SchemaDocumentPropertyArray>
}
Run Code Online (Sandbox Code Playgroud)

如果您需要serde_json::Value使用该to_value方法:

let value = Value { ... };
let json_value = serde_json::to_value(value).expect("Valid json value");
Run Code Online (Sandbox Code Playgroud)