sharp_pencil/json.rs
1//! This module implements helpers for the JSON support in Pencil.
2
3use serde::Serialize;
4use serde_json;
5
6use wrappers::{Response};
7use types::{PencilResult, PenUserError, UserError};
8
9
10/// Creates a view result with the JSON representation of the given object
11/// with an *application/json* mimetype. Example usage:
12///
13/// ```ignore
14/// extern crate rustc_serialize;
15///
16/// use sharp_pencil::{Request, PencilResult, jsonify};
17///
18/// #[derive(RustcEncodable)]
19/// struct User {
20/// id: u8,
21/// name: String,
22/// }
23///
24/// fn get_user(_: &mut Request) -> PencilResult {
25/// let user = User {
26/// id: 1,
27/// name: String::from("admin"),
28/// };
29/// return jsonify(&user);
30/// }
31/// ```
32pub fn jsonify<T: Serialize>(object: &T) -> PencilResult {
33 match serde_json::to_string(object) {
34 Ok(encoded) => {
35 let mut response = Response::from(encoded);
36 response.set_content_type("application/json");
37 Ok(response)
38 },
39 Err(err) => {
40 let error = UserError::new(format!("Json encoder error: {}", err));
41 Err(PenUserError(error))
42 },
43 }
44}