Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can you map serde_json names to different struct values?

In the serde_json library, is it possible to parse json and map one property name to a different property name in the Rust struct?

For example, parse this json:

{
    "json_name": 3
}

into this struct:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

StructName { struct_name: 3 }

Notice that "json_name" and "struct_name" are different.

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading