jsonrustrust-rocket

How to use `json` in Rocket?


I followed the quickstart guide. Now I'm trying to return some super simple JSON and the documentation is wrong and there's no way to submit a ticket without getting on IRC.

error[E0432]: unresolved import `rocket::serde::json`
 --> src/main.rs:2:20
  |
2 | use rocket::serde::json::Json;
  |                    ^^^^ could not find `json` in `serde`

For more information about this error, try `rustc --explain E0432`.
error: could not compile `my-api` due to previous error

This is my code:

[package]
name = "my-api"
version = "0.1.0"
edition = "2021"
publish = false

[dependencies]
rocket = "0.5.0-rc.1"
serde = "1.0.130"
#[macro_use] extern crate rocket;
use rocket::serde::{Serialize, json::Json};

#[derive(Serialize)]
struct Location {
    lat: String,
    lng: String,
}

#[get("/?<lat>&<lng>")]
fn location(lat: &str, lng: &str) -> Json<Location> {
    Json(Location {
        lat: 111.1111.to_string(),
        lng: 222.2222.to_string(),
    })
}

#[launch]
fn rocket() -> _ {
    rocket::build().mount("/", routes![location])
}

If you go here you'll see this is almost a direct copy/paste from the documentation. I don't know enough of Rust to troubleshoot dependency errors.


Solution

  • The json feature for rocket needs to be explicitly turned on in your Cargo.toml.

    [package]
    name = "my-api"
    version = "0.1.0"
    edition = "2018"  // cut back for testing with nixpkgs-provided rust
    publish = false
    
    [dependencies]
    serde = "1.0.130"
    
    [dependencies.rocket]
    version = "0.5.0-rc.1"
    features = ["json"]
    

    This is documented in a comment in the Rocket source which generates the document here.