Search code examples
rustserdeactix-web

The trait Serialize is not implemented despite being implemented?


I'm using actix-web for creating an app for reclaiming packets, then inserting them into MongoDB database. I have a struct

 #[derive(Serialize, Deserialize, Debug)]
    pub struct Gyro{
        /// GYRO FRONT + MIDDLE
        pub x0x800: [i32; 12],
        //A1X, A1Y, A1Z, A2X, A2Y, A2Z, G1X, G1Y, G1Z, G2X, G2Y, G2Z

        /// GYRO BACK
        pub x0x402: [i32; 4],
        //Motion_GPS_CAN, Vehicle_GPS_CAN, X_Angle_GPS, Y_Angle_GPS

        ///GYRO BACK
        pub x0x403: [i32; 4],
        //Z_Angle_GPS, X_Acceleration, Y_Acceleration, Z_Acceleration
    }

And I didn't have problems while deserializing packets into the struct, yet when I try to serialize them into BSON for insertion into mongoDB I am getting this error

if let Ok(bson::Bson::Document(doc)) = bson::to_bson(&packet) {
                                                   ^^^^^^^ the trait `Serialize` is not implemented for `Json<Gyro>

Despite me correctly implementing Serialize in the struct as well as having

use serde::{Serialize, Deserialize};

in the crate, it simply doesn't work. I even checked my dependencies using crate tree -d and all of them were using the same serde version. Here's my cargo.toml

[dependencies]
actix-web = "3.1.0"
env_logger = "0.7"
serde = { version = "1.0.117", features = ["derive"] }
mongodb = "1.1.1"
bson = "1.1.0"

Is there a hidden issue I can't seem to notice, or is there another issue in dependencies?


Solution

  • The issue is that you're trying to serialize a value of type Json<Gyro>, not Gyro. Assuming this is the actix-web Json type, it doesn't implement Serialize. You'll need to either unwrap it by using &packet.into_inner() (which consumes the value) or referencing the inner value with &*packet or &packet.0.