diff --git a/CHANGELOG.md b/CHANGELOG.md index da435c86..3c54589d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,9 @@ project adheres to [Semantic Versioning](http://semver.org/). ### Added - Add support for map (de)serialization. +- Add support for `#[serde(flatten)]` (de)serialization ([#20]). + +[#20]: https://github.com/CosmWasm/serde-json-wasm/issues/20 ### Changed diff --git a/src/de/mod.rs b/src/de/mod.rs index edb56131..1c6fd50d 100644 --- a/src/de/mod.rs +++ b/src/de/mod.rs @@ -687,7 +687,7 @@ where #[cfg(test)] mod tests { use super::from_str; - use serde_derive::Deserialize; + use serde_derive::{Deserialize, Serialize}; #[derive(Debug, Deserialize, PartialEq)] enum Type { @@ -1018,6 +1018,39 @@ mod tests { assert_eq!(serde_json::from_str::(r#"null"#).unwrap(), Nothing); } + #[test] + fn struct_with_flatten() { + #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] + struct Pagination { + limit: u64, + offset: u64, + total: u64, + } + + #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] + struct Users { + users: Vec, + + #[serde(flatten)] + pagination: Pagination, + } + + let expected = Users { + users: vec!["joe".to_string(), "alice".to_string()], + pagination: Pagination { + offset: 100, + limit: 20, + total: 102, + }, + }; + + assert_eq!( + from_str::(r#"{"users":["joe","alice"],"limit":20,"offset":100,"total":102}"#) + .unwrap(), + expected, + ); + } + #[test] fn ignoring_extra_fields() { #[derive(Debug, Deserialize, PartialEq)] diff --git a/src/ser/mod.rs b/src/ser/mod.rs index db009914..f6160638 100644 --- a/src/ser/mod.rs +++ b/src/ser/mod.rs @@ -539,7 +539,7 @@ impl ser::SerializeStructVariant for Unreachable { mod tests { use super::to_string; - use serde_derive::Serialize; + use serde_derive::{Deserialize, Serialize}; #[test] fn bool() { @@ -988,6 +988,43 @@ mod tests { ); } + #[test] + fn struct_with_flatten() { + #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] + struct Pagination { + limit: u64, + offset: u64, + total: u64, + } + + #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] + struct Users { + users: Vec, + + #[serde(flatten)] + pagination: Pagination, + } + + let users = Users { + users: vec!["joe".to_string(), "alice".to_string()], + pagination: Pagination { + offset: 100, + limit: 20, + total: 102, + }, + }; + + assert_eq!( + to_string(&users).unwrap(), + r#"{"users":["joe","alice"],"limit":20,"offset":100,"total":102}"# + ); + assert_eq!( + to_string(&users).unwrap(), + serde_json::to_string(&users).unwrap(), + "serialization must match serde_json implementation" + ); + } + #[test] fn btree_map() { use std::collections::BTreeMap;