Question
How do I avoid generating JSON when serializing a value that is null or a default value?
The serde_json::to_string()
function will generate a string which may include null
for an Option<T>
, or 0
for a u32
. This makes the output larger, so I want to ignore these sorts of values.
I want to simplify the JSON string output of the following structure:
use serde_derive::Serialize; // 1.0.82
#[derive(Serialize)]
pub struct WeightWithOptionGroup {
pub group: Option<String>,
pub proportion: u32,
}
When group
is None
and proportion
is 0, the JSON string should be "{}"
Thanks for the answerHow do I change Serde's default implementation to return an empty object instead of null?, it can resolve Option
problem, but for 0
there is none solution.
46 27657
46