Home > Software design >  How to read response JSON as structs when they contain hyphens in key names?
How to read response JSON as structs when they contain hyphens in key names?

Time:03-03

I am querying an API for some data but their keys have hyphens instead of underscores in their names, and since I can't have hyphens in struct field names, I am unable to cast it.

For example, my struct:

pub struct Example {
    user_id: String,
    name: String,
}

and the received json is like

{
    "user-id": "abc",
    "name": "John"
}

Right now i'm doing this but i can't because i can't directly cast it

let res = client
    .get("SOME-URL")
    .header("x-api-key", APP_ID)
    .send()
    .await?;

let response_body: Example = res.json().await?;

CodePudding user response:

If it is just a single attribute, you can use:

If it is all of them (kebab case, or other styling) you can use:

#[serde(rename_all = "kebab-case")]

#[derive(Deserialize, Debug)]
pub struct Example {
    #[serde(alias = "user-id")]
    user_id: String,
    name: String,
}

playground

  • Related