You can use a field attribute to tell serde that you want to use a name other than what you called the field in Rust. This tells serde that the json field data
should be written to the struct's new_data
field:
use serde::Deserialize;
use serde_json;
static JSON: &'static str = r#"{ "data": 4 }"#;
#[derive(Deserialize)]
struct Foo {
data: u8,
}
#[derive(Deserialize)]
struct Bar {
#[serde(rename = "data")]
new_data: u8,
}
fn main() {
let foo: Foo = serde_json::from_str(JSON).unwrap();
let bar: Bar = serde_json::from_str(JSON).unwrap();
assert_eq!(foo.data, bar.new_data);
}
Note: you'll need the derive
crate feature for serde (serde = { version = "1.0", features = ["derive"] }
in Cargo.toml
), and make sure that the structs you're using with the JSON data have the appropriate derive macros.