#serde #deserialize #serialize

serde_either

Simple set to enums to deserialize and serialize data that can either be string, struct or vec

4 releases

0.2.1 Aug 13, 2022
0.2.0 May 21, 2021
0.1.1 Apr 17, 2021
0.1.0 Apr 17, 2021

#338 in Data structures

Download history 24/week @ 2022-11-26 5/week @ 2022-12-03 7/week @ 2022-12-10 3/week @ 2022-12-17 3/week @ 2022-12-24 13/week @ 2022-12-31 1/week @ 2023-01-07 1/week @ 2023-01-14 4/week @ 2023-01-21 8/week @ 2023-01-28 59/week @ 2023-02-04 31/week @ 2023-02-11 53/week @ 2023-02-18 68/week @ 2023-02-25 149/week @ 2023-03-04 119/week @ 2023-03-11

400 downloads per month
Used in ckandex

MIT/Apache

12KB
193 lines

Serde Either

serde_either is a simple library that provides a few enums that enables you to deserialize and serialize values that can have string, struct or vec forms.

Let's say you want to deserialize a json for a Book, and that json has an "authors" field and this files can be either a string or a object like:

{
  "authors": "John Smith"
}

Or like

{
  "authors": {
    "first_name": "John",
    "last_name": "Smith"
  }
}

All you need to do is create a data structure like this:

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");

And if you need to also capture a possible array of authors like this:

{
  "authors": [
    {
      "first_name": "John",
      "last_name": "Smith"
    },
    {
      "first_name": "Michael",
      "last_name": "Smith"
    },
  ]
}

Then all you need to change is:

use serde_either::StringOrStructOrVec;

// ...

#[derive(Serialize, Deserialize)]
struct Book {
  pub authors: StringOrStructOrVec<Authors, Vec<Authors>>
}

License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~335–510KB
~11K SLoC