Axum serde serialization from handler loses serde changes

32 views Asked by At

My route is supposed to return a shape like from Mongodb to client:

[
  {
    id: 1234,
    name: "john",
    createdDate: 2024-02-28T14:04:09.466Z,
    updatedDate: 2024-02-28T14:04:09.466Z
  }
]

I can see this shape in my println in the handler.

pub async fn get_lists() -> impl IntoResponse {
    println!("get_lists");

    let data: Vec<database::ListDocument> = database::get_list().await.unwrap();
    println!("get_lists: {:?}", data); // <------ CLOSER TO CORRECT/CHANGED SHAPE

    Json(data) <------- INCORRECT/UNCHANGED SHAPE
}

The struct is:

#[derive(Debug, Serialize, Deserialize)]
pub struct ListDocument {
    #[serde(rename = "_id", with = "bson::serde_helpers::hex_string_as_object_id")]
    id: String,
    name: String,
    #[serde(with = "bson::serde_helpers::chrono_datetime_as_bson_datetime")]
    createdDate: chrono::DateTime<chrono::Utc>,
    #[serde(with = "bson::serde_helpers::chrono_datetime_as_bson_datetime")]
    updatedDate: chrono::DateTime<chrono::Utc>,
}

Println shape looks like:

[ ListDocument 
  { 
    id: "65df3d5934761793df5fbe46", 
    name: "My List", 
    createdDate: 2024-02-28T14:04:09.466Z, 
    updatedDate: 2024-02-28T14:04:09.466Z 
  }

Incorrect shape lookes like:

[
  {
    "_id":{"$oid":"65df3d5934761793df5fbe46"},
    "name":"My List",
    "createdDate":{"$date":{"$numberLong":"1709129049466"}},
    "updatedDate":{"$date":{"$numberLong":"1709129049466"}}
  }
]

How do I return the changed shape all the way through the router to the client?

I can find answers not using serde and axum but how do I fix this with serde and axum.

0

There are 0 answers