Search code examples
rustrust-chrono

How to use chrono::DateTime<Utc> with schemars::JsonSchema?


I'm trying to implement JsonSchema for a struct like this:

use chrono::{DateTime, Utc};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Default, Clone, JsonSchema)]
pub struct ArticleResponse {
    pub pub_time: Option<DateTime<Utc>>,
}

But this outputs an error when compiling:

error[E0277]: the trait bound `DateTime<Utc>: JsonSchema` is not satisfied
  --> src/main.rs:4:50
   |
 4 | #[derive(Serialize, Deserialize, Default, Clone, JsonSchema)]
   |                                                  ^^^^^^^^^^ the trait `JsonSchema` is not implemented for `DateTime<Utc>`

What should I do to implement JsonSchema for ArticleResponse?


Solution

  • To quote the docs:

    For example, to implement JsonSchema on types from chrono, enable it as a feature in the schemars dependency in your Cargo.toml like so:

    [dependencies]
    schemars = { version = "0.8", features = ["chrono"] }