serde_with
serde_with copied to clipboard
Convert a map to a list of single elements
Sometimes it makes sense to deserialize a map as a list of single items, i.e., Vec<T>
. The map-key becomes a special field in T
.
{
"id0": {
"field_a": ...,
...
},
"id1": {...},
"id2": {...},
}
This could be converted to:
struct Data {
id: IdType,
field_a: ...,
field_b: ...,
}
Prior art: https://crates.io/crates/serde-key-value-vec-map
EDIT: This is available as serde_with::EnumMap
A slightly different transformation is between a map and a Vec
of enums like #375.
The key is the tag of the enum.
Serialize a Vec
of externally tagged enums to a map with the map key being the external tag.
vec![
EnumValue::Int(123),
EnumValue::String("FooBar".to_string()),
EnumValue::Int(456),
EnumValue::String("XXX".to_string()),
EnumValue::Unit,
EnumValue::Tuple(1, "Middle".to_string(), false),
EnumValue::Struct {
a: 666,
b: "BBB".to_string(),
c: true,
},
],
gets converted into this JSON
{
"Int": 123,
"String": "FooBar",
"Int": 456,
"String": "XXX",
"Unit": null,
"Tuple": [
1,
"Middle",
false
],
"Struct": {
"a": 666,
"b": "BBB",
"c": true
}
}
This got requested here: https://github.com/serde-rs/json/issues/743
There is an implementation for the first post in #555. You both indicated interest in the feature. If you still need the feature and could leave some feedback at #555, that would be very much appreciated. @ncfavier @latk