Crate serializers[][src]

Serializers

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.

Example

#[macro_use]
extern crate serializers;

use serializers::*;

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

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

serializer! {
    serialize_user: User {
        attr(id)
        attr(name)
        has_one(country, serialize_country)
        has_many(friends, serialize_user)
    }
}

serializer! {
    serialize_country: 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 = serialize_user.serialize(&bob);

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

See the macro docs for more information about its options.

No macros for me

The easiest way to define serializers is using the serializer! macro, however if you don't wish to do so you can define serializers like so:

fn serialize_user(user: &User, b: &mut Builder) {
    b.attr("id", &user.id);
    b.attr("name", &user.name);
    b.has_one("country", &user.country, &serialize_country);
    b.has_many("friends", &user.friends, &serialize_user);
}

Any function with such a signature will automatically become a Serializer.

Using the serializer function afterwards works the same as if you used the macro.

Macros

serializer

This macro is the primary way to make serializers. See the top level docs for an example.

Structs

Builder

The struct responsible for gathering keys and values for the JSON.

Traits

Serializer

The trait you implement in order to make a serializer. The key-value pairs will be gathered in the Builder and turned into a JSON string by ToJson.

ToJson

The trait responsible for actually compiling the JSON.