Test
Test

Reputation: 1720

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:

StructName { struct_name: 3 }

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

Upvotes: 1

Views: 2672

Answers (1)

Jeremy Meadows
Jeremy Meadows

Reputation: 2561

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.

Upvotes: 7

Related Questions