Field rename
- Rust course
- Intermediate
- Lesson 104/115
- 4 min
Rename fields with #[serde(rename)].
Field renaming
Rust fields use snake_case, while many JSON APIs use camelCase. serde attributes map the names without changing the code:
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Kullanici {
ad: String,
kayit_tarihi: String, // "kayitTarihi"
#[serde(rename = "e-posta")]
eposta: String, // "e-posta"
}rename_all applies to all fields, rename to a single one. Options: camelCase, PascalCase, kebab-case, SCREAMING_SNAKE_CASE.
Writing the conversion by hand
The conversion that rename_all = "camelCase" does is simple: drop the underscore and uppercase the next letter:
fn camel(s: &str) -> String {
let mut sonuc = String::new();
let mut buyut = false;
for c in s.chars() {
if c == '_' {
buyut = true;
} else if buyut {
sonuc.extend(c.to_uppercase());
buyut = false;
} else {
sonuc.push(c);
}
}
sonuc
}Practice camelCase conversion
Write the camel function above. Print the results for "kayit_tarihi", "ad" and "son_giris_zamani" separated by spaces.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn camel(s: &str) -> String {
let mut sonuc = String::new();
let mut buyut = false;
for c in s.chars() {
if c == '_' {
buyut = true;
} else if buyut {
sonuc.extend(c.to_uppercase());
buyut = false;
} else {
sonuc.push(c);
}
}
sonuc
}
fn main() {
println!("{} {} {}", camel("kayit_tarihi"), camel("ad"), camel("son_giris_zamani"));
}Expected output
kayitTarihi ad sonGirisZamani
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is <code>#[serde(alias = "name")]</code> for?
- Produces two names when writing
- It doesn't compile
- Accepts an extra name when reading; uses the real name when writing Correct answer
- Hides the field
Explanation: It's handy for reading both old and new JSON formats at the same time.
2 Rename all
#[serde(____ = "camelCase")]
struct Kullanici {
kayit_tarihi: String,
}
#[serde(rename_all = "camelCase")]
struct Kullanici {
kayit_tarihi: String,
}
Explanation: rename_all applies a naming rule to all fields.
3 Field and camelCase JSON name
| Term | Meaning |
|---|---|
ad |
ad |
kayit_tarihi |
kayitTarihi |
son_giris_zamani |
sonGirisZamani |
#[serde(rename = "e-posta")] |
e-posta |