Rename 'contrib::JSON' to 'contrib::Json'.

This commit is contained in:
Sergio Benitez 2017-07-12 15:11:41 -07:00
parent 70bc97c322
commit 65886c8c4e
11 changed files with 62 additions and 61 deletions

View File

@ -21,14 +21,14 @@ pub use serde_json::error::Error as SerdeError;
/// ## Receiving JSON
///
/// If you're receiving JSON data, simply add a `data` parameter to your route
/// arguments and ensure the type of the parameter is a `JSON<T>`, where `T` is
/// arguments and ensure the type of the parameter is a `Json<T>`, where `T` is
/// some type you'd like to parse from JSON. `T` must implement `Deserialize` or
/// `DeserializeOwned` from [Serde](https://github.com/serde-rs/json). The data
/// is parsed from the HTTP request body.
///
/// ```rust,ignore
/// #[post("/users/", format = "application/json", data = "<user>")]
/// fn new_user(user: JSON<User>) {
/// fn new_user(user: Json<User>) {
/// ...
/// }
/// ```
@ -40,16 +40,16 @@ pub use serde_json::error::Error as SerdeError;
///
/// ## Sending JSON
///
/// If you're responding with JSON data, return a `JSON<T>` type, where `T`
/// If you're responding with JSON data, return a `Json<T>` type, where `T`
/// implements `Serialize` from [Serde](https://github.com/serde-rs/json). The
/// content type of the response is set to `application/json` automatically.
///
/// ```rust,ignore
/// #[get("/users/<id>")]
/// fn user(id: usize) -> JSON<User> {
/// fn user(id: usize) -> Json<User> {
/// let user_from_id = User::from(id);
/// ...
/// JSON(user_from_id)
/// Json(user_from_id)
/// }
/// ```
///
@ -67,16 +67,16 @@ pub use serde_json::error::Error as SerdeError;
/// json = 5242880
/// ```
#[derive(Debug)]
pub struct JSON<T = Value>(pub T);
pub struct Json<T = Value>(pub T);
impl<T> JSON<T> {
impl<T> Json<T> {
/// Consumes the JSON wrapper and returns the wrapped item.
///
/// # Example
/// ```rust
/// # use rocket_contrib::JSON;
/// # use rocket_contrib::Json;
/// let string = "Hello".to_string();
/// let my_json = JSON(string);
/// let my_json = Json(string);
/// assert_eq!(my_json.into_inner(), "Hello".to_string());
/// ```
#[inline(always)]
@ -88,7 +88,7 @@ impl<T> JSON<T> {
/// Default limit for JSON is 1MB.
const LIMIT: u64 = 1 << 20;
impl<T: DeserializeOwned> FromData for JSON<T> {
impl<T: DeserializeOwned> FromData for Json<T> {
type Error = SerdeError;
fn from_data(request: &Request, data: Data) -> data::Outcome<Self, SerdeError> {
@ -99,7 +99,7 @@ impl<T: DeserializeOwned> FromData for JSON<T> {
let size_limit = request.limits().get("json").unwrap_or(LIMIT);
serde_json::from_reader(data.open().take(size_limit))
.map(|val| JSON(val))
.map(|val| Json(val))
.map_err(|e| { error_!("Couldn't parse JSON body: {:?}", e); e })
.into_outcome(Status::BadRequest)
}
@ -108,7 +108,7 @@ impl<T: DeserializeOwned> FromData for JSON<T> {
/// Serializes the wrapped value into JSON. Returns a response with Content-Type
/// JSON and a fixed-size body with the serialized value. If serialization
/// fails, an `Err` of `Status::InternalServerError` is returned.
impl<T: Serialize> Responder<'static> for JSON<T> {
impl<T: Serialize> Responder<'static> for Json<T> {
fn respond_to(self, req: &Request) -> response::Result<'static> {
serde_json::to_string(&self.0).map(|string| {
content::JSON(string).respond_to(req).unwrap()
@ -119,7 +119,7 @@ impl<T: Serialize> Responder<'static> for JSON<T> {
}
}
impl<T> Deref for JSON<T> {
impl<T> Deref for Json<T> {
type Target = T;
#[inline(always)]
@ -128,7 +128,7 @@ impl<T> Deref for JSON<T> {
}
}
impl<T> DerefMut for JSON<T> {
impl<T> DerefMut for Json<T> {
#[inline(always)]
fn deref_mut<'a>(&'a mut self) -> &'a mut T {
&mut self.0
@ -147,17 +147,18 @@ impl<T> DerefMut for JSON<T> {
/// ```
///
/// The return type of a macro invocation is
/// [Value](/rocket_contrib/enum.Value.html). This is the default value for the
/// type parameter of [JSON](/rocket_contrib/struct.JSON.html) and as such, you
/// can return `JSON` without specifying the type. A value created with this
/// macro can be returned from a handler as follows:
/// [`Value`](/rocket_contrib/enum.Value.html). This is the default type for the
/// type parameter of [`Json`](/rocket_contrib/struct.Json.html) and as such,
/// you can return `Json` without specifying the type using a `json!` value for
/// `Json`. A value created with this macro can be returned from a handler as
/// follows:
///
/// ```rust,ignore
/// use rocket_contrib::JSON;
/// use rocket_contrib::Json;
///
/// #[get("/json")]
/// fn get_json() -> JSON {
/// JSON(json!({
/// fn get_json() -> Json {
/// Json(json!({
/// "key": "value",
/// "array": [1, 2, 3, 4]
/// }))

View File

@ -17,7 +17,7 @@
//! common modules exposed by default. The present feature list is below, with
//! an asterisk next to the features that are enabled by default:
//!
//! * [json*](struct.JSON.html)
//! * [json*](struct.Json.html)
//! * [msgpack](struct.MsgPack.html)
//! * [handlebars_templates](struct.Template.html)
//! * [tera_templates](struct.Template.html)
@ -54,7 +54,7 @@ extern crate serde_json;
pub mod json;
#[cfg(feature = "json")]
pub use json::{JSON, SerdeError, Value};
pub use json::{Json, SerdeError, Value};
#[cfg(feature = "msgpack")]
#[doc(hidden)]

View File

@ -8,7 +8,7 @@ extern crate serde_json;
#[cfg(test)] mod tests;
use rocket_contrib::{JSON, Value};
use rocket_contrib::{Json, Value};
use rocket::State;
use std::collections::HashMap;
use std::sync::Mutex;
@ -27,35 +27,35 @@ struct Message {
// TODO: This example can be improved by using `route` with multiple HTTP verbs.
#[post("/<id>", format = "application/json", data = "<message>")]
fn new(id: ID, message: JSON<Message>, map: State<MessageMap>) -> JSON<Value> {
fn new(id: ID, message: Json<Message>, map: State<MessageMap>) -> Json<Value> {
let mut hashmap = map.lock().expect("map lock.");
if hashmap.contains_key(&id) {
JSON(json!({
Json(json!({
"status": "error",
"reason": "ID exists. Try put."
}))
} else {
hashmap.insert(id, message.0.contents);
JSON(json!({ "status": "ok" }))
Json(json!({ "status": "ok" }))
}
}
#[put("/<id>", format = "application/json", data = "<message>")]
fn update(id: ID, message: JSON<Message>, map: State<MessageMap>) -> Option<JSON<Value>> {
fn update(id: ID, message: Json<Message>, map: State<MessageMap>) -> Option<Json<Value>> {
let mut hashmap = map.lock().unwrap();
if hashmap.contains_key(&id) {
hashmap.insert(id, message.0.contents);
Some(JSON(json!({ "status": "ok" })))
Some(Json(json!({ "status": "ok" })))
} else {
None
}
}
#[get("/<id>", format = "application/json")]
fn get(id: ID, map: State<MessageMap>) -> Option<JSON<Message>> {
fn get(id: ID, map: State<MessageMap>) -> Option<Json<Message>> {
let hashmap = map.lock().unwrap();
hashmap.get(&id).map(|contents| {
JSON(Message {
Json(Message {
id: Some(id),
contents: contents.clone()
})
@ -63,8 +63,8 @@ fn get(id: ID, map: State<MessageMap>) -> Option<JSON<Message>> {
}
#[error(404)]
fn not_found() -> JSON<Value> {
JSON(json!({
fn not_found() -> Json<Value> {
Json(json!({
"status": "error",
"reason": "Resource was not found."
}))

View File

@ -139,7 +139,7 @@ impl<'a, S, E> IntoOutcome<S, (Status, E), Data> for Result<S, E> {
/// }
/// ```
///
/// `Person` has a custom serialization format, so the built-in `JSON` type
/// `Person` has a custom serialization format, so the built-in `Json` type
/// doesn't suffice. The format is `<name>:<age>` with `Content-Type:
/// application/x-person`. You'd like to use `Person` as a `FromData` type so
/// that you can retrieve it directly from a client's request body:

View File

@ -430,12 +430,12 @@ impl<'r> Request<'r> {
///
/// # Example
///
/// Invoke the `JSON<T>` request guard.
/// Invoke the `Json<T>` request guard.
///
/// ```rust,ignore
/// use rocket_contrib::JSON;
/// use rocket_contrib::Json;
///
/// let outcome = request.guard::<JSON<T>>();
/// let outcome = request.guard::<Json<T>>();
/// ```
///
/// Retrieve managed state inside of a guard implementation:

View File

@ -15,9 +15,9 @@
//!
//! # Contrib
//!
//! The [contrib crate](/rocket_contrib) contains several useful `Responder`s
//! including [Template](/rocket_contrib/struct.Template.html) and
//! [JSON](/rocket_contrib/struct.JSON.html).
//! The [`contrib` crate](/rocket_contrib) contains several useful `Responder`s
//! including [`Template`](/rocket_contrib/struct.Template.html) and
//! [`Json`](/rocket_contrib/struct.Json.html).
mod responder;
mod redirect;

View File

@ -233,7 +233,7 @@ As an example, consider the following route:
```rust
#[post("/user", format = "application/json", data = "<user>")]
fn new_user(user: JSON<User>) -> T { ... }
fn new_user(user: Json<User>) -> T { ... }
```
The `format` parameter in the `post` attribute declares that only incoming
@ -250,7 +250,7 @@ As an example, consider the following route:
```rust
#[get("/user/<id>", format = "application/json")]
fn user(id: usize) -> JSON<User> { ... }
fn user(id: usize) -> Json<User> { ... }
```
The `format` parameter in the `get` attribute declares that only incoming
@ -630,7 +630,7 @@ examples on GitHub provide further illustrations.
### JSON
Handling JSON data is no harder: simply use the
[`JSON`](https://api.rocket.rs/rocket_contrib/struct.JSON.html) type:
[`Json`](https://api.rocket.rs/rocket_contrib/struct.Json.html) type:
```rust
#[derive(Deserialize)]
@ -640,10 +640,10 @@ struct Task {
}
#[post("/todo", data = "<task>")]
fn new(task: JSON<Task>) -> String { ... }
fn new(task: Json<Task>) -> String { ... }
```
The only condition is that the generic type in `JSON` implements the
The only condition is that the generic type in `Json` implements the
`Deserialize` trait from [Serde](https://github.com/serde-rs/json). See the
[JSON example] on GitHub for a complete example.

View File

@ -54,13 +54,13 @@ an `&'static str` to JSON, you can use the [`content::JSON`] type as follows:
use rocket::response::content;
#[get("/")]
fn json() -> content::JSON<&'static str> {
content::JSON("{ 'hi': 'world' }")
fn json() -> content::Json<&'static str> {
content::Json("{ 'hi': 'world' }")
}
```
[`Accepted`]: https://api.rocket.rs/rocket/response/status/struct.Accepted.html
[`content::JSON`]: https://api.rocket.rs/rocket/response/content/struct.JSON.html
[`content::JSON`]: https://api.rocket.rs/rocket/response/content/struct.Json.html
### Errors
@ -210,7 +210,7 @@ fn stream() -> io::Result<Stream<UnixStream>> {
### JSON
The [`JSON`] responder in [`rocket_contrib`] allows you to easily respond with
well-formed JSON data: simply return a value of type `JSON<T>` where `T` is the
well-formed JSON data: simply return a value of type `Json<T>` where `T` is the
type of a structure to serialize into JSON. The type `T` must implement the
[`Serialize`] trait from [`serde`], which can be automatically derived.
@ -218,13 +218,13 @@ An an example, to respond with the JSON value of a `Task` structure, we might
write:
```rust
use rocket_contrib::JSON;
use rocket_contrib::Json;
#[derive(Serialize)]
struct Task { ... }
#[get("/todo")]
fn todo() -> JSON<Task> { ... }
fn todo() -> Json<Task> { ... }
```
The `JSON` type serializes the structure into JSON, sets the Content-Type to
@ -233,7 +233,7 @@ fails, a **500 - Internal Server Error** is returned.
The [JSON example on GitHub] provides further illustration.
[`JSON`]: https://api.rocket.rs/rocket_contrib/struct.JSON.html
[`JSON`]: https://api.rocket.rs/rocket_contrib/struct.Json.html
[`Serialize`]: https://docs.serde.rs/serde/trait.Serialize.html
[`serde`]: https://docs.serde.rs/serde/
[JSON example on GitHub]: https://github.com/SergioBenitez/Rocket/tree/v0.2.8/examples/json

View File

@ -287,9 +287,9 @@ array of some `Task` structures that are fetched from a database:
```rust
#[get("/tasks")]
fn get_tasks(conn: DbConn) -> QueryResult<JSON<Vec<Task>>> {
fn get_tasks(conn: DbConn) -> QueryResult<Json<Vec<Task>>> {
all_tasks.order(tasks::id.desc())
.load::<Task>(&conn)
.map(|tasks| JSON(tasks))
.map(|tasks| Json(tasks))
}
```

View File

@ -107,12 +107,12 @@ code = '''
}
#[put("/<id>", data = "<message>")]
fn update(id: ID, message: JSON<Message>) -> JSON<Value> {
fn update(id: ID, message: Json<Message>) -> Json<Value> {
if DB.contains_key(&id) {
DB.insert(id, &message.contents);
JSON(json!{ "status": "ok" })
Json(json!{ "status": "ok" })
} else {
JSON(json!{ "status": "error" })
Json(json!{ "status": "error" })
}
}
'''

View File

@ -73,9 +73,9 @@ the `user_form` parameter. The
Rocket type that knows how to parse web forms into structures. Rocket will
automatically attempt to parse the request body into the `Form` and call the
`login` handler if parsing succeeds. Other built-in `FromData` types include
[Data](https://api.rocket.rs/rocket/struct.Data.html),
[JSON](https://api.rocket.rs/rocket_contrib/struct.JSON.html), and
[Flash](https://api.rocket.rs/rocket/response/struct.Flash.html)
[`Data`](https://api.rocket.rs/rocket/struct.Data.html),
[`Json`](https://api.rocket.rs/rocket_contrib/struct.Json.html), and
[`Flash`](https://api.rocket.rs/rocket/response/struct.Flash.html)
'''
[[panels]]
@ -219,7 +219,7 @@ If the function above is used as a handler, for instance, then the type `T` must
implement `Responder`. Rocket provides many useful responder types out of the
box. They include:
* `JSON<T>`: Serializes the structure T into JSON and returns it to
* `Json<T>`: Serializes the structure T into JSON and returns it to
the client.
* `Template`: Renders a template file and returns it to the client.
* `Redirect`: Returns a properly formatted HTTP redirect.