How can I apply a transformation to a field before serialization?
For example, how can I ensure that the fields lat
and lon
in this struct definition are rounded to at most 6 decimal places before being serialized?
#[derive(Debug, Serialize)]
struct NodeLocation {
#[serde(rename = "nodeId")]
id: u32,
lat: f32,
lon: f32,
}
The
serialize_with
attributeYou can use the
serialize_with
attribute to provide a custom serialization function for your field:(I've rounded to the nearest integer to avoid the topic "what is best way to round a float to k decimal places").
Implement
serde::Serialize
The other semi-manual approach is to create a separate struct with auto-derived serialization, and implement your serialization using that:
Notably, this allows you to also add or remove fields as the "inner" serialized type can do basically whatever it wants.