How do I use Serde to serialize a HashMap with structs as keys to JSON?

You can use serde_as from the serde_with crate to encode the HashMap as a sequence of key-value pairs:

use serde_with::serde_as; // 1.5.1

#[serde_as]
#[derive(Serialize, Deserialize, Debug)]
struct Bar {
    #[serde_as(as = "Vec<(_, _)>")]
    x: HashMap<Foo, f64>,
}

Which will serialize to (and deserialize from) this:

{
  "x":[
    [{"x": 0}, 0.0],
    [{"x": 1}, 0.0],
    [{"x": 2}, 0.0]
  ]
}

There is likely some overhead from converting the HashMap to Vec, but this can be very convenient.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)