The structs in my crate are generic over associated types from another crate that don't implement serde. Eg
struct Foo<F: SomeExtTrait> {
a: F,
b: F,
}
Since F
comes from another trait, i used attributes serialize_with
and deserialize_with
and i can check that both serialization and de-serialization work for
struct Foo<F: SomeExtTrait> {
#[serde(serialize_with = "to_bytes", deserialize_with = "from_bytes")]
a: F,
#[serde(serialize_with = "to_bytes", deserialize_with = "from_bytes")]
b: F,
}
where to_bytes
and from_bytes
can convert F
to and from bytes respectively. I get this serialization
{"a":[190,8, ...], "b": [82,229, ...]} when using serde_json for above.
Now i want to serialize the following
struct Bar<F: SomeExtTrait> {
a: F,
b: [F; 2],
c: Vec<F>
}
I intend to serialize each F into separate byte array so using serde-json for above, i want to get
{"a":[190,8, ...], "b": [[82,229, ...], [206,46]], "c": [[29,1,..], [143,90,..], [78,190..], ... ]}
But I don't see a way to serialize the above without implementing Serialize
for the struct? Is there a way where I can use serialize_with
attribute
I was looking at implementing a version of to_bytes
that takes a vector and was thinking of using serialize_seq
but suck on the following.
pub fn f_vec_to_bytes_vec<S, F>(elems: &Vec<F>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer
{
let mut seq = serializer.serialize_seq(Some(elems.len()))?;
for i in 0..elems.len() {
// The following doesn't work as I have not defined Serialize trait for F
// seq.serialize_element(&elems[i])?;
}
seq.end();
}