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

1

6

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?;
Suburban answered 2/3, 2022 at 20:49 Comment(2)
Are you using serde? If so, you have a couple options: (1) use #[serde(rename_all = "kebab-case")] at the struct level, (2) use #[serde(rename = "user-id")] at the field level.Pelfrey
Thank you, that's what I will do, I am using serdeSuburban
D
11

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

Doctor answered 2/3, 2022 at 21:24 Comment(1)
Yes, it's just a couple attributes, I am going to try this.Suburban

© 2022 - 2024 — McMap. All rights reserved.