使用serialize_with
字段属性:
use serde::{Deserialize, Serialize, Serializer}; // 1.0.106
use serde_json; // 1.0.52
use std::collections::{BTreeMap, HashMap};
#[derive(Serialize, Deserialize, Default)]
struct MyStruct {
#[serde(serialize_with = "ordered_map")]
map: HashMap<String, String>,
}
fn ordered_map<S>(value: &HashMap<String, String>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let ordered: BTreeMap<_, _> = value.iter().collect();
ordered.serialize(serializer)
}
fn main() {
let mut m = MyStruct::default();
m.map.insert("gamma".into(), "3".into());
m.map.insert("alpha".into(), "1".into());
m.map.insert("beta".into(), "2".into());
println!("{}", serde_json::to_string_pretty(&m).unwrap());
}
在这里,我选择BTreeMap
从 中重建一个整体HashMap
,然后重用现有的序列化实现。
{
"map": {
"alpha": "1",
"beta": "2",
"gamma": "3"
}
}