#serde_json #json #serializer

serializers

Easily create multiple serializers for the same type

7 releases

0.2.3 Nov 17, 2018
0.2.2 Nov 12, 2018
0.1.2 Sep 30, 2018

#198 in Encoding

Download history 3/week @ 2018-10-07 51/week @ 2018-10-14 4/week @ 2018-10-21 29/week @ 2018-10-28 24/week @ 2018-11-04 50/week @ 2018-11-11 12/week @ 2018-11-18 42/week @ 2018-11-25 17/week @ 2018-12-02 13/week @ 2018-12-09 7/week @ 2018-12-16 60/week @ 2018-12-23 6/week @ 2018-12-30 15/week @ 2019-01-06 14/week @ 2019-01-13

100 downloads per month

MIT license

20KB
316 lines

Serializers

Build Status Crates.io Documentation

Normally when using "serde_json" and #[derive(Serialize)] you only can have one JSON representation for a type, however sometimes you might need another one which has more or less data.

This crate makes it easy to create "serializers" that take some value and turn it into JSON. You get to decide for each serializer which type it serializes, and which fields and associations it includes.

Install

[dependencies]
serializers = "0.2.3"

Example

#[macro_use]
extern crate serializers;
#[macro_use]
extern crate serde_json;

use serializers::*;

struct User {
    id: u64,
    name: String,
    country: Country,
    friends: Vec<User>,
}

#[derive(Clone)]
struct Country {
    id: u64,
}

serializer! {
    #[derive(Debug, Copy, Clone)]
    struct UserSerializer<User> {
        attr(id)
        attr(name)
        has_one(country, CountrySerializer)
        has_many(friends, UserSerializer)
    }
}

serializer! {
    #[derive(Debug, Copy, Clone)]
    struct CountrySerializer<Country> {
        attr(id)
    }
}

fn main() {
    let denmark = Country {
        id: 1,
    };

    let bob = User {
        id: 1,
        name: "Bob".to_string(),
        country: denmark.clone(),
        friends: vec![
            User {
                id: 2,
                name: "Alice".to_string(),
                country: denmark.clone(),
                friends: vec![],
            }
        ],
    };

    let json: String = UserSerializer::serialize(&bob);

    assert_eq!(
        json,
        json!({
            "country": { "id": 1 },
            "friends": [
                {
                    "country": { "id": 1 },
                    "friends": [],
                    "name": "Alice",
                    "id": 2
                }
            ],
            "name": "Bob",
            "id": 1
        }).to_string(),
    );
}

See the API docs for more info.

Dependencies

~715KB
~15K SLoC