Home > OS >  the trait `Serialize` is not implemented for `Jsonb`
the trait `Serialize` is not implemented for `Jsonb`

Time:05-01

when I define jsonb in rust diesel diesel = { version = "1.4.7", features = ["postgres","serde_json"] } like this:

#[macro_use]
extern crate diesel;

use diesel::pg::types::sql_types::Jsonb;
use rocket::serde::Deserialize;
use rocket::serde::Serialize;

fn main() {
    println!("hello")
}

#[derive(Queryable,Debug,Serialize,Deserialize,Default)]
//#[table_name = "test"]
pub struct Test {
    pub id: i64,
    pub tags: Jsonb,
}

the compiler shows error:

the trait `Deserialize<'_>` is not implemented for `Jsonb`

what should I do to make the diesel handle the PostgreSQL jsonb data type?

CodePudding user response:

I think you are using the Jsonb type incorrectly. It's a database column type which determines how the data is encoded in the database itself but is not intended to be used direclty in your application data structures and messaging.

Assuming your table is defined like this:

table! {
    test {
        id -> Integer,
        tags -> Jsonb,
    }
}

You can convert rows into a struct like this:

#[derive(Queryable, Debug, Serialize, Deserialize)]
pub struct Test {
    pub id: i64,
    pub tags: serde_json::Value,
}
  • Related