Hello All,
I am trying to Serialize/Deserialize a structure of this type:
#[derive(Deserialize, Default, Clone, Debug, Serialize)]
struct Metrics {
metric: String,
#[serde(deserialize_with = "deserialize_vec", serialize_with = "serialize_vec")]
data: Option<Vec<f64>>,
metric_type: String,
}
with custom Serializer/Deserializer adapters.
The possible JSON that can come are of these 2 type:
let input_1 = r#"{
"metric": "thread0",
"data": [ 9.0, 12.0, 16.0, 2.0, null, 7.0, null, null, 8.0 ],
"metric_type": "thread"
}"#;
let input_2 = r#"{
"metric": "thread1",
"data": null,
"metric_type": "thread"
}"#;
where the data field itself can be null or the vec can contain null
values. So far, I have managed to write custom Serializer/Deserializer when the data field is of type Vec<f64>
only ( inspired from : Deserialize JSON array and replace null elements with zeros - #2 by nickelc ).
Also, I was able to write Serializer for data : Option<Vec<f64>>
as follows:
fn serialize_vec<S>(
to_serialize_vec_option: &Option<Vec<f64>>,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match *to_serialize_vec_option {
Some(ref value) => {
let mut temp = Vec::<Option<f64>>::new();
for i in value {
if i.is_nan() {
temp.push(None);
} else {
temp.push(Some(*i));
}
}
serializer.serialize_some(&temp)
}
None => serializer.serialize_none(),
}
}
But I am facing difficulty writing Deserializer for data: Option<Vec<f64>>
where either the Option can be null or the vector itself contains null values and I convert them as NAN while deserializing. Could anyone guide me how to write custom Deserializer function that can be used for Option<Vec<f64>>
which can parse the given 2 input string ?
Many thanks in advance to the Rust Community.