#serialization #deserialize #serde #deserialize-json #enums #string #forms

serde_either

简单地将枚举集转换为可以序列化和反序列化字符串、结构体或vec的数据

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数据结构

Download history 96/week @ 2024-03-13 127/week @ 2024-03-20 148/week @ 2024-03-27 116/week @ 2024-04-03 123/week @ 2024-04-10 106/week @ 2024-04-17 124/week @ 2024-04-24 211/week @ 2024-05-01 565/week @ 2024-05-08 384/week @ 2024-05-15 241/week @ 2024-05-22 545/week @ 2024-05-29 385/week @ 2024-06-05 444/week @ 2024-06-12 260/week @ 2024-06-19 400/week @ 2024-06-26

1,566 每月下载量
用于 4 个crate(直接使用2个)

MIT/Apache

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.0MIT许可证下授权。

除非您明确声明,否则您有意提交的任何贡献,根据Apache-2.0许可证的定义,都应按上述方式双重授权,不附加任何额外条款或条件。

依赖项

~335–630KB
~14K SLoC