candid icon indicating copy to clipboard operation
candid copied to clipboard

Support serde rename_all

Open chenyan-dfinity opened this issue 5 years ago • 4 comments

#[serde(rename_all = "snake_case")]
pub enum CanisterStatusType {
    Running,
    Stopping,
    Stopped,
}

Discussed https://github.com/dfinity-lab/dfinity/pull/4812

chenyan-dfinity avatar Aug 05 '20 17:08 chenyan-dfinity

We experienced this problem today. This issue makes it impossible to have a struct that derives both CandidType and serde Serialize. For example:

#[derive(CandidType, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Person {
    first_name: String,
    last_name: String,
}

In this case:

  • serde_json::from_value(serde_json::json!(person)) -> OK
  • candid::Decode!(candid::Encode!(person), Person) -> Error

Is there any plan to fix it?

ufoscout avatar Feb 28 '23 09:02 ufoscout

As a workaround, you can use #[serde(rename = "")] instead.

struct Person {
    #[serde(rename = "firstName")]
    first_name: String,
    #[serde(rename = "lastName")]
    last_name: String,
}

chenyan-dfinity avatar Feb 28 '23 16:02 chenyan-dfinity

@chenyan-dfinity Yes, that's a valid workaround even if some of my structs have more than 30 fields :disappointed_relieved:

Anyway, while this is not supported, you should break the compilation or at least inform the user with a warning, in fact, this compiles but fails at runtime when a canister calls an endpoint that uses this type:

#[derive(CandidType, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Person {
    first_name: String,
    last_name: String,
}

ufoscout avatar Mar 01 '23 07:03 ufoscout

+1 to initial request to support #[serde(rename_all = "snake_case")].

maksymar avatar Oct 09 '24 18:10 maksymar