serde_as on struct or struct tuple values #518
-
Hi! I have a type defined as follows, and it currently serializes/deserializes to an array of numbers. I'm hoping to make the type always serialize as base64 anywhere it is used. #[derive(serde::Serialize, serde::Deserialize)]
pub struct VecM<T>(Vec<T>); All the examples I've found of using When I attempt to use it on a struct like as follows I get the following error: #[derive(serde::Serialize, serde::Deserialize)]
#[serde_as(as = "Base64")]
pub struct VecM<T>(Vec<T>);
When I attempt to use it on the struct field like as follows I get the following error: #[derive(serde::Serialize, serde::Deserialize)]
pub struct VecM<T>(
#[serde_as(as = "Base64")]
Vec<T>
);
Is there a way to attach the base64 serializer to a type rather than at each location it is used in a field? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
The Your last example looks almost right. You need an additional attribute before the derive. Try adding If your |
Beta Was this translation helpful? Give feedback.
The
serde_as
attribute is a replacement for serde's with attribute. As such, it only works on fields and not on structs. https://docs.rs/serde_with/2.0.1/serde_with/guide/serde_as/index.html#switching-from-serdes-with-to-serde_asYour last example looks almost right. You need an additional attribute before the derive. Try adding
#[serde_with::serde_as]
at the beginning.If your
Base64
type is also fromserde_with
there is another problem. TheBase64
type only works with types implementingAsRef<[u8]>
, butVec<T>
is not one of them. It only works for the special case when yourT
isu8
.