简体   繁体   中英

How to read response JSON as structs when they contain hyphens in key names?

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?;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM