Search code examples
rustrust-rocket

Why is Rocket's `Json` type not found in the `content` module?


Today I found that a project that previously worked no longer compiles. Here is a minimal example that reproduces my sudden error:

use rocket::{get, launch, routes};
use rocket::response::content;

#[get("/health")]
pub fn health() -> content::Json<String> {
    content::Json("ok".parse().unwrap())
}

#[launch]
async fn rocket() -> _ {
    rocket::build().mount("/actuator", routes![health])
}
error[E0412]: cannot find type `Json` in module `content`
 --> src\main.rs:5:29
  |
5 | pub fn health() -> content::Json<String> {
  |                             ^^^^ not found in `content`
  |
help: consider importing this struct
  |
1 | use rocket::serde::json::Json;
  |

error[E0425]: cannot find function, tuple struct or tuple variant `Json` in module `content`
 --> src\main.rs:6:14
  |
6 |     content::Json("ok".parse().unwrap())
  |              ^^^^ not found in `content`
  |
help: consider importing this tuple struct
  |
1 | use rocket::serde::json::Json;
  |

I am using cargo 1.59.0 (49d8809dc 2022-02-10) and rustc 1.59.0 (9d1b2106e 2022-02-23). And here are my dependencies:

[dependencies]
rocket = { version = "0.5.0-rc.1", features = ["json"] }

The content::Json is supposed to come from Rocket and should be enabled by the cargo feature above. It definitely worked the past. What should I do to fix this problem? How did this happen?


Solution

  • The content module was changed between Rocket release candidates. Compare the documentation for 0.5.0-rc.1 and 0.5.0-rc.2. The Json type moved to rocket::serde::json::Json. So your code should look like this:

    use rocket::serde::json::Json;
    
    pub fn health() -> Json<String> {
        Json("ok".parse().unwrap())
    }
    

    But I did not upgrade the rocket version, I am still using 0.5.0-rc.1

    It seems you did, albeit unknowingly. This can happen if cargo update was ran or you simply didn't preserve your Cargo.lock file (or something recreated it). It is somewhat dubious if rc.1 should be seen as compatible with rc.2, but regardless, you can lock your dependency to a specific version by prefixing it with = if you want to stay on rc.1:

    [dependencies]
    rocket = { version = "=0.5.0-rc.1", features = ["json"] }