I'm trying to serialze and deserialze struct MyVec
, which has a field time_vec
: Vec<chrono::NaiveDateTime>
as following:
use serde::{ Serialize, Deserialize, Serializer, ser::SerializeSeq, de::{self, Error, SeqAccess} };
type dt = chrono::NaiveDateTime;
type vdt = Vec<dt>;
#[derive(Clone, Serialize, Deserialize, Default, Debug)]
struct MyVec {
#[serde(deserialize_with = "deserialize_vec_datetime", serialize_with = "serialize_vec_datetime")]
time_vec: Vec<dt>
}
pub fn serialize_vec_datetime<S>(id: &vdt, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = s.serialize_seq(Some(id.len()))?;
for e in id {
let es = e.timestamp_millis();
seq.serialize_element(&es)?;
}
seq.end()
}
pub fn deserialize_vec_datetime<'de, D>(deserializer: D) -> Result<vdt, D::Error>
where
D: de::Deserializer<'de>,
{
struct VecI64;
impl<'de> de::Visitor<'de> for VecI64 {
type Value = Vec<i64>;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("a string containing json data")
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
let mut res: Self::Value = Vec::with_capacity(seq.size_hint().unwrap_or_default());
while let Some(ele) = seq.next_element()? {
res.push(ele);
}
Ok(res)
}
}
let res_vec_i64 = deserializer.deserialize_seq(VecI64)?;
let res = res_vec_i64.into_iter().map(|x| dt::from_timestamp_millis(x).unwrap()).collect::<Vec<_>>();
Ok(res)
}
I serialize and deserialize the field time_vec
with methods serialize_with
and deserialize_with
, so the before Vec<dt>
is serialized, it converted to a Vec<i64>
first.
But as can be seen in the last three lines from the codes, it construct two Vec
s: res_vec_i64
and res
. When the time_vec
is huge, two Vec
s consume too much memory. So I'm figuring out that how can I only make one Vec
to get the job down?