typestar

Custom field conversions in Rust

serialize_with and deserialize_with hand one field off to your own function.

use serde::{Deserialize, Deserializer, Serialize, Serializer};

#[derive(Debug, Serialize, Deserialize)]
struct Reading {
    sensor: String,
    #[serde(with = "millis")]
    elapsed: f64,
}

mod millis {
    use super::*;

    pub fn serialize<S: Serializer>(v: &f64, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_u64((v * 1000.0).round() as u64)
    }

    pub fn deserialize<'de, D>(d: D) -> Result<f64, D::Error>
    where
        D: Deserializer<'de>,
    {
        let ms = u64::deserialize(d)?;
        Ok(ms as f64 / 1000.0)
    }
}

fn main() -> Result<(), serde_json::Error> {
    let r = Reading { sensor: "clock".to_string(), elapsed: 1.25 };
    let json = serde_json::to_string(&r)?;
    println!("{json}");
    println!("{:?}", serde_json::from_str::<Reading>(&json)?);
    Ok(())
}

How it works

  1. with sets both directions at once for a field.
  2. The functions take a serializer or a deserializer.
  3. Use it for timestamps, units, and legacy encodings.

Keywords and builtins used here

The run, in numbers

Lines
32
Characters to type
715
Tokens
227
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 124 seconds.

Type this snippet

Step 1 of 2 in Custom & failure, step 9 of 11 in Serde & JSON.

← Previous Next →