Crate serde_aux [] [src]

serde-aux

A serde auxiliary library.

Installation

Add the following dependency to your project's Cargo.toml:

[dependencies]
serde-aux = "0.1"

And add this to your root file:

#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate serde_aux;
extern crate serde;

use std::str::FromStr;
use std::num::{ParseIntError, ParseFloatError};

use serde::{Deserialize, Deserializer};

#[derive(Serialize, Deserialize, Debug)]
struct B {
    #[serde(deserialize_with = "serde_aux::deserialize_string_from_number")]
    i: String,
    #[serde(deserialize_with = "serde_aux::deserialize_number_from_string")]
    j: u64,
}

#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct FloatId(f64);

impl FromStr for FloatId {
    type Err = ParseFloatError;

    fn from_str(s: &str) -> Result<FloatId, Self::Err> {
        Ok(FloatId(f64::from_str(s)?))
    }
}

#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
struct IntId(u64);

impl FromStr for IntId {
    type Err = ParseIntError;

    fn from_str(s: &str) -> Result<IntId, Self::Err> {
        Ok(IntId(u64::from_str(s)?))
    }
}

#[derive(Serialize, Deserialize, Debug)]
struct A {
    #[serde(deserialize_with = "serde_aux::deserialize_number_from_string")]
    int_id: IntId,
    #[serde(deserialize_with = "serde_aux::deserialize_number_from_string")]
    float_id: FloatId,
}

fn main() {
    let j = r#" { "i": "foo", "j": "123" } "#;
    let b: B = serde_json::from_str(j).unwrap();
    assert_eq!(b.i, "foo");
    assert_eq!(b.j, 123);

    let j = r#" { "i": -13, "j": 232 } "#;
    let b: B = serde_json::from_str(j).unwrap();
    assert_eq!(b.i, "-13");
    assert_eq!(b.j, 232);

    let j = r#" { "int_id": 655, "float_id": 432.897 } "#;
    let a: A = serde_json::from_str(j).unwrap();
    assert_eq!(a.int_id, IntId(655));
    assert_eq!(a.float_id, FloatId(432.897));

    let j = r#" { "int_id": "221", "float_id": "123.456" } "#;
    let a: A = serde_json::from_str(j).unwrap();
    assert_eq!(a.int_id, IntId(221));
    assert_eq!(a.float_id, FloatId(123.456));
}

Functions

deserialize_number_from_string

Deserializes a number from string or a number.

deserialize_string_from_number

Deserializes string from a number. If the original value is a number value, it will be converted to a string.