Bạn có thể sử dụng để cung cấp serialize_with
attributea custom serialization function cho lĩnh vực của bạn:
#[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,
}
(Tôi đã làm tròn đến số nguyên gần nhất để tránh chủ đề "Cách tốt nhất để làm tròn một phao để k là gì số thập phân ").
Các bán thủ công cách tiếp cận khác là tạo ra một cấu trúc riêng biệt với serialization tự động có nguồn gốc, và thực hiện tuần tự bằng cách sử dụng rằng:
impl Serialize for NodeLocation {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
// Implement your preprocessing in `from`.
RoundedNodeLocation::from(loc).serialize(s)
}
}
thủ thực hiện 'Serialize'? – Kroltan