Home > Software design >  How to map JSON keys with spaces in them to fields in a struct when deserializing
How to map JSON keys with spaces in them to fields in a struct when deserializing

Time:02-05

I am trying to pull deserialized data from a stock quote API and store it in a struct from the JSON, but the problem is that the keys from the source have spaces and a period in them.

The JSON I get back looks like this:

"01. symbol": "AAPL",
"02. open": "174.4800",
"03. high": "176.2399",
"04. low": "172.1200",
"05. price": "172.9000",
"06. volume": "89418074",
"07. latest trading day": "2022-02-03",
"08. previous close": "175.8400",
"09. change": "-2.9400",
"10. change percent": "-1.6720%"

I am trying put it in a struct named Json like this:

let result = &response.json::<Json>().await?;

but I can't figure out how to name the fields of the struct to line up with the names in the JSON because there are spaces in them. Is there a way to name the fields in the struct one way, then map those fields to fields of different names in the JSON object?

I want the struct to look like this:

#[derive(Deserialize, Debug)]
struct Json {
    symbol: String,
    open: String,
    high: String, 
    ...
}

CodePudding user response:

You can specify the JSON field name in an attribute

#[derive(Deserialize, Debug)]
struct Json {
    #[serde(rename = "01. symbol")]
    symbol: String,
    #[serde(rename = "02. open")]
    open: String,
    #[serde(rename = "03. high")]
    high: String, 
    ...
}
  •  Tags:  
  • Related