serde-map-to-array

This crate provides unofficial serde helpers to support converting a map to a sequence of named key-value pairs for human-readable encoding formats.
This allows for a stable schema in the face of a mutable map.
For example, let's say we have a map containing the values
[(1, "one"), (2, "two"), (3, "three")]
. Encoded to JSON this is:
We cannot specify a schema for this JSON Object though unless the contents of the map are
guaranteed to always contain three entries under the keys 1
, 2
and 3
.
This crate allows for such a map to be encoded to a JSON Array of Objects, each containing exactly two elements with static names:
for which a schema can be generated.
Furthermore, this avoids encoding the key type of the map to a string.
By default, the key-value pairs will be given the labels "key" and "value", but this can be
modified by providing your own labels via a struct which implements
KeyValueLabels
.
Note that for binary (non-human-readable) encoding formats, default serialization and deserialization is retained.
no_std
By default, the crate is no_std
, but uses alloc
. In this case, support for BTreeMap
s and
BTreeMap
-like types is provided.
If feature std
is enabled then support for HashMap
s and HashMap
-like types is also
provided, but no_std
support is disabled.
Examples
Using the default field values "key" and "value"
use BTreeMap;
use ;
use BTreeMapToArray;
let mut data = default;
data.inner.insert;
data.inner.insert;
assert_eq!;
Using non-default field labels
use HashMap;
use ;
use ;
;
let mut data = default;
data.inner.insert;
data.inner.insert;
// The hashmap orders the entries randomly.
let expected_json = if *data.inner.keys.next.unwrap == 1 else ;
assert_eq!;
Using a custom BTreeMap
-like type
use ;
use ;
use ;
;
/// We need to implement `IntoIterator` to allow serialization.
/// We need to implement `From<BTreeMap>` to allow deserialization.
Using a HashMap
with a non-standard hasher
use HashMap;
use ;
use HashBuildHasher;
use ;
Using a custom HashMap
-like type
use ;
use ;
use ;
;
/// We need to implement `IntoIterator` to allow serialization.
/// We need to implement `From<HashMap>` to allow deserialization.
JSON Schema Support
Support for generating JSON schemas via schemars
can be
enabled by setting the feature json-schema
.
By default, the schema name of the KeyValue struct will be set to
"KeyValue_for_{K::schema_name()}_and_{V::schema_name()}"
, and the struct and its key and value
fields will have no descriptions (normally generated from doc comments for the struct and its
fields). Each of these can be modified by providing your own values via a struct which implements
KeyValueJsonSchema
.
License
serde-map-to-array
is distributed under the terms of both the MIT license and the Apache License (Version 2.0).
See LICENSE-MIT and LICENSE-APACHE for details.