Renaming fields in Rust
Rust names stay snake_case while the JSON keeps whatever the API expects.
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Step {
step_index: u32,
tour_slug: String,
#[serde(rename = "tpm3")]
target_tpm: u32,
#[serde(alias = "name")]
title: String,
}
fn main() -> Result<(), serde_json::Error> {
let raw = r#"{"stepIndex":0,"tourSlug":"traits","tpm3":100,
"name":"Trait objects"}"#;
let step: Step = serde_json::from_str(raw)?;
println!("{:?}", step);
println!("{}", serde_json::to_string(&step)?);
Ok(())
}
How it works
rename_allconverts every field in one go.renamehandles the one field that breaks the pattern.aliasaccepts an old key while writing the new one.
Keywords and builtins used here
OkResultStepStringfnletmainstructu32use
The run, in numbers
- Lines
- 21
- Characters to type
- 506
- Tokens
- 119
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 68 seconds.
Step 1 of 3 in Field attributes, step 4 of 11 in Serde & JSON.