0

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?

pretzelhammer
  • 13,874
  • 15
  • 47
  • 98
Patrox27
  • 3
  • 2

1 Answers1

4

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.

apetranzilla
  • 5,331
  • 27
  • 34
  • I think `&packet.0` is more general, since it won't unnecessarily consume `packet`. – Sven Marnach Oct 23 '20 at 19:08
  • That would also work, it just comes down to stylistic preference. I think `into_inner` is a little more clear and explicit assuming the value isn't needed later. Since the type also implements `Deref` it should also be possible to use `&*packet` as another way to avoid consuming the value. – apetranzilla Oct 23 '20 at 19:10
  • I like `&*packet` even better. I don't agree it's a stylistic difference though, and I don't like consuming `packet` if you only need a reference to the inner value. – Sven Marnach Oct 23 '20 at 19:22
  • Fair enough, I've edited my answer to include `&*packet` and `&packet.0`. – apetranzilla Oct 23 '20 at 20:41