Rust Rocket and serde serialization to camelCase not working

124 views Asked by At

I have a Rocket API route, which returns JSON and I want to set it to camelCase, but after hours I cannot figure out why setting #[serde(rename_all = "camelCase")] in my model is not working properly.

This is my model:

use crate::schema::*;
use chrono::NaiveDateTime;
use diesel::{AsChangeset, Identifiable, Queryable};
//use rocket::serde::{Deserialize, Serialize};
use serde::Deserialize;
use serde::Serialize;

#[derive(Queryable, AsChangeset, PartialEq, Deserialize, Serialize, Identifiable, Debug)]
#[diesel(table_name=categories)]
#[serde(rename_all = "camelCase")]
pub struct ProductCategory {
    pub id: i32,
    pub system_name: Option<String>,
    pub title: Option<String>,
    pub assignable: Option<bool>,
    pub parent_id: Option<i32>,
    pub created_at: NaiveDateTime,
    pub updated_at: NaiveDateTime,
    pub permalink: Option<String>,
    pub image: Option<String>,

And this is my route function:

use rocket::response::status::Custom;
use rocket::serde::json::{Json, Value};

use crate::api::{server_error, DbConn};
use crate::repositories::product_categories::ProductCategoriesRepository;

#[rocket::get("/v2/product_categories")]
pub async fn get_product_categories(db: DbConn) -> Result<Json<Value>, Custom<Value>> {
    db.run(move |c| {
        ProductCategoriesRepository::find_all(c)
            .map(|product_categories| {
                let serialized = serde_json::to_string(&product_categories).unwrap();
                println!("Serialized JSON: {}", serialized);
                let again = Json(serde_json::from_str(&serialized).unwrap());
                println!("Serialized JSON: {:?}", again);
                again
            })
            .map_err(|e| server_error(e.into()))
    })
    .await
}

This is my Cargo.toml:

[package]
name = "test_api"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
rocket = { version = "0.5.0-rc.3", features = ["json"] }
rocket_sync_db_pools = { version = "0.1.0-rc.3", features = ["diesel_mysql_pool"] }
rocket_contrib = "0.4.11"
diesel = { version = "2.0.3", features = ["mysql", "chrono", "128-column-tables", "serde_json"] }
chrono = { version = "0.4.24", features = ["serde"] }
serde = { version = "1.0.160", features = ["derive"] }
serde_json = { version = "1.0.96" }
log = "0.4.17"
dotenv = "0.15.0"
clap = "4.2.2"
validator = { version = "0.16.0", features = ["derive"] }

[dev-dependencies]
reqwest = { version = "0.11.16", features = ["json", "blocking"] }

And this is also repository method which is selecting from DB.

use crate::schema::*;
use diesel::prelude::*;
use crate::models::product_category::ProductCategoryResult;

pub struct ProductCategoriesRepository;

impl ProductCategoriesRepository {
    pub fn find_all(c: &mut MysqlConnection) -> QueryResult<Vec<ProductCategoryResult>> {
        let parent_ids = vec![2, 21];
        categories::table
            .select(
                (categories::id,
                 categories::system_name,
                 categories::title,
                 categories::permalink,
                 categories::image
)
            )
            .filter(categories::parent_id.eq_any(&parent_ids))
            .load::<ProductCategoryResult>(c)
    }
}

I am running out of ideas why returned json is still snake cased :(

Please any suggestions?

0

There are 0 answers