如何在序列化之前将转换应用于字段?
例如,如何确保此结构定义中的字段lat
和lon
在序列化之前舍入到最多6个小数位?
#[derive(Debug, Serialize)]
struct NodeLocation {
#[serde(rename = "nodeId")]
id: u32,
lat: f32,
lon: f32,
}
答案 0 :(得分:7)
serialize_with
属性您可以使用serialize_with
attribute为您的字段提供a custom serialization function:
#[macro_use]
extern crate serde_derive;
extern crate serde;
use serde::Serializer;
fn round_serialize<S>(x: &f32, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
s.serialize_f32(x.round())
}
#[derive(Debug, Serialize)]
pub struct NodeLocation {
#[serde(rename = "nodeId")]
id: u32,
#[serde(serialize_with = "round_serialize")]
lat: f32,
#[serde(serialize_with = "round_serialize")]
lon: f32,
}
(我已四舍五入到最接近的整数,以避免“将浮点数舍入到小数点后k的最佳方法”这一主题。)
serde::Serialize
另一种半手动方法是使用自动派生序列化创建单独的结构,并使用以下方法实现序列化:
#[derive(Debug)]
pub struct NodeLocation {
id: u32,
lat: f32,
lon: f32,
}
impl serde::Serialize for NodeLocation {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
// Implement your preprocessing in `from`.
RoundedNodeLocation::from(self).serialize(s)
}
}
#[derive(Debug, Serialize)]
pub struct RoundedNodeLocation {
#[serde(rename = "nodeId")]
id: u32,
lat: f32,
lon: f32,
}
impl<'a> From<&'a NodeLocation> for RoundedNodeLocation {
fn from(other: &'a NodeLocation) -> Self {
Self {
id: other.id,
lat: other.lat.round(),
lon: other.lon.round(),
}
}
}
值得注意的是,这允许您添加或删除字段,因为“内部”序列化类型基本上可以做任何事情。