Skip to content

Wrap Structs with an alternate root element during serialization and deserialization using Serde

License

Apache-2.0, MIT licenses found

Licenses found

Apache-2.0
LICENSE-APACHE
MIT
LICENSE-MIT
Notifications You must be signed in to change notification settings

balajisivaraman/serde_struct_wrapper

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

15 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Serde Struct Wrapper

Build Status Latest Version Rust Documentation

This crate provides macros that enable wrapping Rust structs with alternate root keys during serialization and deserialization using Serde. In principle, it offers a functionality similar to the @JsonRootName annotation for Java's Jackson framework.

Note that this crate is primarily intended to be used in conjunction with the serde_json crate. It has not been tested with other data formats.

Usage

Add this to your Cargo.toml:

serde_struct_wrapper = "0.3"

You can use the serde_with_root! macro as shown below to both serialize and deserialize a Struct with an alternate root key. (Please note the use of the #[serde(remote = "Self")] attribute on the Struct letting SerDe know of the alernate Serialize and Deserialize implementations provided by the macro.)

extern crate serde;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate serde_struct_wrapper;
#[derive(Serialize, Deserialize, Debug)]
#[serde(remote = "Self")]
pub struct Point {
    pub x: i32,
    pub y: i32,
}
serde_with_root!("point": Point);

The above will let you serialize/deserialize a JSON structure like the following:

{
    "point": {
        "x": 1,
        "y": 2
    }
}

For getting only the Serializer implementation, use the serialize_with_root! macro; likewise with the deserialize_with_root! macro for only the Deserializer implementation.

License

Serde is licensed under either of

at your option.

Credits

The initial Deserializer implementation for this crate was provided by David Tolnay in this Github issue. The code provided there was used as the base to provide this crate.

About

Wrap Structs with an alternate root element during serialization and deserialization using Serde

Topics

Resources

License

Apache-2.0, MIT licenses found

Licenses found

Apache-2.0
LICENSE-APACHE
MIT
LICENSE-MIT

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages