Crates.io | miniserde-enum |
lib.rs | miniserde-enum |
version | 0.1.3 |
source | src |
created_at | 2019-11-18 12:01:55.759015 |
updated_at | 2019-11-19 14:20:53.493556 |
description | Derive macros for miniserde on enums |
homepage | |
repository | https://github.com/etwyniel/miniserde-enum |
max_upload_size | |
id | 182198 |
size | 59,672 |
This crate exposes derive macros for miniserde's Serialize
and Deserialize
traits on enums.
The goal of this crate is to provide enum support like that of Serde for miniserde (see Serde's list of enum representations).
use miniserde::{Deserialize, json};
use miniserde_enum::Deserialize_enum;
#[derive(Deserialize_enum, Debug, PartialEq)]
enum External {
A(i32),
#[serde(rename = "renamedB")]
B(i32, String),
C {
x: i32,
},
D,
}
use External::*;
let example = r#"[{"A":21},{"renamedB":[42,"everything"]},{"C":{"x":2}},"D"]"#;
let actual: Vec<External> = json::from_str(example).unwrap();
let expected = [A(21), B(42, "everything".to_string()), C { x: 2 }, D];
assert_eq!(actual, expected);
use miniserde::{json, Serialize};
use miniserde_enum::Serialize_enum;
#[serde(tag = "type")]
#[derive(Serialize_enum)]
enum Internal {
A,
#[serde(rename = "renamedB")]
B,
C {
x: i32,
},
}
use Internal::*;
let example = [A, B, C { x: 2 }];
let actual = json::to_string(&example[..]);
let expected = r#"[{"type":"A"},{"type":"renamedB"},{"type":"C","x":2}]"#;
assert_eq!(actual, expected);
More examples can be found in the tests directory.
Deserializing internally tagged enums and adjacently tagged enums requires the tag to be the first key in the object, otherwise from_str will return an error.
Additionally, not every enum representation is currently supported (see TODO).
Externally tagged enums
Internally tagged enums
Untagged enums
Adjacently tagged enums