Serializing a `Vec<chrono::NaiveDateTime>` with using `serde.`

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 Vecs: res_vec_i64 and res. When the time_vec is huge, two Vecs consume too much memory. So I'm figuring out that how can I only make one Vec to get the job down?

Thank you very much for paid attention for this asking, I have figure out this with following implementation:

pub fn deserialize_vec_dt<'de, D>(deserializer: D) -> Result<vdt, D::Error>
where
    D: de::Deserializer<'de>, {
    struct VecEle;

    impl<'de> de::Visitor<'de> for VecEle {
        type Value  = dt;
        
        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
            formatter.write_str("a string")
        }

        fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
        where
            E: Error,
        {
            let res = dt::from_timestamp_millis(v).unwrap();
            Ok(res)
        }
    }

    impl<'de> DeserializeSeed<'de> for VecEle {
        type Value = dt;
        fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
        where
            D: Deserializer<'de>
        {
            deserializer.deserialize_i64(self)
        }
    }



    struct VecDt;

    impl<'de> de::Visitor<'de> for VecDt {
        type Value = Vec<dt>;
    
        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_seed(VecEle)? {
                res.push(ele);
            }
            Ok(res)
        }
    }
    deserializer.deserialize_seq(VecDt)
}

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.