#serialize-deserialize #sequence #user #serialization #third-party #serde #hash-map

serde-mappable-seq

Unnoficial third-party serde (de)serializers for mappable sequences

1 unstable release

0.1.0 Sep 15, 2019

#1468 in Encoding

Download history 6/week @ 2024-07-24 12/week @ 2024-07-31 14/week @ 2024-08-07 8/week @ 2024-08-14 5/week @ 2024-08-21 6/week @ 2024-08-28 15/week @ 2024-09-04 14/week @ 2024-09-11 28/week @ 2024-09-18 30/week @ 2024-09-25 22/week @ 2024-10-02 6/week @ 2024-10-09 8/week @ 2024-10-16 14/week @ 2024-10-23 16/week @ 2024-10-30 14/week @ 2024-11-06

54 downloads per month

ISC license

9KB
110 lines

license-badge docs-badge rust badge

serde-mappable-seq

An unofficial third-party crate to deserialize sequences of keyed structs into HashMaps or BTreeMaps and vice versa.

Sometimes APIs will provide a list of instances of a resource in a sequence, such as a list of users. Imagine this JSON payload:

{
  "data": {
    "users": [
      {
        "id": 1,
        "name": "foo"
      }
    ]
  },
  "links": {}
}

If you want to get something by ID, you're going to either need to post-process it manually (slightly annoying) or loop through to find the user with the ID (slightly costly).

serde-mappable-seq makes turning a sequence of a resource into a keyed map easy.

Installation

This library requires at least Rust 1.31.0.

Add this to your Cargo.toml:

[dependencies]
serde-mappable-seq = "0.1"

Examples

Deserialize a struct containing a sequence of 2 users into a HashMap, keyed by their IDs:

use serde_derive::{Deserialize, Serialize};
use serde_mappable_seq::Key;
use std::collections::HashMap;

#[derive(Deserialize, Serialize)]
struct User {
    id: u64,
    name: String,
}

impl Key<'_, u64> for User {
    fn key(&self) -> u64 {
        self.id
    }
}

#[derive(Deserialize, Serialize)]
struct Response {
    #[serde(with = "serde_mappable_seq")]
    users: HashMap<u64, User>,
}

# fn main() -> Result<(), Box<dyn std::error::Error>> {
let input = r#"{
  "users": [
    {
      "id": 1,
      "name": "foo"
    }
  ]
}"#;

let response = serde_json::from_str::<Response>(input)?;
assert_eq!("foo", response.users.get(&1).unwrap().name);

// Now serialize it back and make sure it's the same as the original input.
assert_eq!(input, serde_json::to_string_pretty(&response)?);
# Ok(()) }

Serializing the instance of the response struct in the above example will net back the original input.

License

ISC.

Dependencies

~100–335KB