pub trait ObjectScopeSerializer<T, S> {
// Required method
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) -> Value { ... }
}
Expand description
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, ¤t_user, true);
assert_eq!(
json.pointer("/jedi/name").unwrap().as_str().unwrap(),
"Palpatine"
);
assert_eq!(
json.pointer("/jedi/secret").unwrap().as_str().unwrap(),
"Dark side"
);