Trait jsonway::serializer::ObjectScopeSerializer [] [src]

pub trait ObjectScopeSerializer<T, S> {
    fn build(&self, &T, &S, &mut ObjectBuilder);

    fn root(&self) -> Option<&str> { ... }
    fn serialize(&mut self, obj: &T, scope: &S, include_root: bool) -> Json { ... }
}

Provides functionality to create custom JSON presenters for your structs.

Example

use jsonway::{self, ObjectScopeSerializer};
 
struct User {
    id: u64,
    is_admin: bool
}
 
struct Jedi {
    name: String,
    secret: String
}
 
struct JediSerializer;
 
impl jsonway::ObjectScopeSerializer<Jedi, User> for JediSerializer {
    fn root(&self) -> Option<&str> { Some("jedi") }
    fn build(&self, jedi: &Jedi, current_user: &User, json: &mut jsonway::ObjectBuilder) {
        json.set("name", jedi.name.to_string());
 
        if current_user.is_admin {
            json.set("secret", jedi.secret.to_string());
        }
    }
}
 
let jedi = Jedi { 
    name: "Palpatine".to_string(), 
    secret: "Dark side".to_string() 
};

let current_user = User { id: 1, is_admin: true };
let json = JediSerializer.serialize(&jedi, &current_user, true);

assert_eq!(
    json.find_path(&[
        "jedi",
        "name",
    ]).unwrap().as_string().unwrap(), 
    "Palpatine"
);

assert_eq!(
    json.find_path(&[
        "jedi",
        "secret",
    ]).unwrap().as_string().unwrap(), 
    "Dark side"
);

Required Methods

fn build(&self, &T, &S, &mut ObjectBuilder)

Provided Methods

fn root(&self) -> Option<&str>

fn serialize(&mut self, obj: &T, scope: &S, include_root: bool) -> Json

Implementors