4个版本
0.2.1 | 2022年8月13日 |
---|---|
0.2.0 | 2021年5月21日 |
0.1.1 | 2021年4月17日 |
0.1.0 | 2021年4月17日 |
965 在 数据结构
1,566 每月下载量
用于 4 个crate(直接使用2个)
12KB
193 行
Serde Either
serde_either是一个简单的库,提供了一些枚举,使您能够反序列化和序列化具有字符串、结构体或vec形式的数据。
假设您想反序列化一个用于Book的json,并且该json有一个"authors"字段,这些文件可以是字符串或对象,例如
{
"authors": "John Smith"
}
或者像这样
{
"authors": {
"first_name": "John",
"last_name": "Smith"
}
}
您需要做的只是创建一个这样的数据结构
use serde::{Serialize, Deserialize};
use serde_either::StringOrStruct;
use serde_json;
#[derive(Serialize, Deserialize)]
struct Authors {
first_name: String,
last_name: String
}
#[derive(Serialize, Deserialize)]
struct Book {
pub authors: StringOrStruct<Authors>
}
// And StringOrStruct is just a normal enum
impl Book {
fn get_author_name(&self) -> String {
match &self.authors {
StringOrStruct::String(s) => s.to_owned(),
StringOrStruct::Struct(author) => format!("{} {}", &author.first_name, &author.last_name)
}
}
}
let books = r#"[
{
"authors": {
"first_name": "John",
"last_name": "Smith"
}
},
{
"authors": "Michael J. Smith"
}
]"#;
let res: Vec<Book> = serde_json::from_str(books).unwrap();
assert_eq!(res[0].get_author_name(), "John Smith");
assert_eq!(res[1].get_author_name(), "Michael J. Smith");
如果您还需要捕获一个可能的作者数组,例如
{
"authors": [
{
"first_name": "John",
"last_name": "Smith"
},
{
"first_name": "Michael",
"last_name": "Smith"
},
]
}
那么您需要更改的是
use serde_either::StringOrStructOrVec;
// ...
#[derive(Serialize, Deserialize)]
struct Book {
pub authors: StringOrStructOrVec<Authors, Vec<Authors>>
}
许可证
根据您的选择,在Apache License, Version 2.0或MIT许可证下授权。
除非您明确声明,否则您有意提交的任何贡献,根据Apache-2.0许可证的定义,都应按上述方式双重授权,不附加任何额外条款或条件。
依赖项
~335–630KB
~14K SLoC