-1
#[derive(Deserialize, Serialize)]
enum En {
    A(i32),
    B(String)
}

#[derive(Deserialize, Serialize)]
struct Data {
    data: Mutex<HashSet<En>>
}

When using this structure, serializing the struct outputs something like {"data": [{"A": 0}, {"B": "String"}]}, I'd like to remove the list from the json and combine the data into one map ({"data": {"A": 0, "B": "String"}}).

I'd like to keep the HashSet for unique data and to force each variant's type, is there a way to do that without having to implement my own serialize or deserialize methods.

I've tried using serde_as from the serde_with crate with the as type Mutex<HashMap<String, _>>, though I keep getting errors saying "the trait bound HashMap<Same, Same>: SerializeAs<HashSet<En>> is not satisfied"

I have a partial solution using a HashMap instead of a HashSet, though I'd prefer if it was possible to keep using a set.

Ontley
  • 1
  • 5
  • Please give an example of the JSON output you desire. – PitaJ Jan 20 '23 at 17:29
  • It sounds like you just need a separate enum with just the variants `A` and `B`, no data, which you can use as the keys of the hashmap. – BallpointBen Jan 20 '23 at 17:45
  • @PitaJ I edited the post to include an example of wanted output – Ontley Jan 20 '23 at 18:24
  • @BallpointBen do you mean with serde_as? I'm still getting the error with as = "Mutex>" – Ontley Jan 20 '23 at 18:26
  • What should happen if you have two `En::A`‘s in the set? – BallpointBen Jan 20 '23 at 19:52
  • The old one should be replaced, though I guess that can be done with just Eq implementation – Ontley Jan 20 '23 at 21:43
  • Something similar is possible using the `EnumMap` type from `serde_with`. https://docs.rs/serde_with/latest/serde_with/struct.EnumMap.html It does not work with `HashSet`, but only with `Vec`. You receive the "trait bound" error message, because you cannot just write anything in the `serde_as` attribute. Specific combinations are allowed: https://docs.rs/serde_with/2.2.0/serde_with/guide/serde_as_transformations/index.html – jonasbb Jan 20 '23 at 22:06
  • @jonasbb This appears to be working, thank you! – Ontley Jan 21 '23 at 11:23

1 Answers1

0

Using the serde_with crate seems to work

#[serde_as]
#[derive(Deserialize, Serialize)]
struct Data {
    #[serde_as(as = "serde_with::EnumMap")
    data: Mutex<Vec<En>>
}

As a replacement for a HashSet I used the strum crate AsRefStr trait, implemented PartialEq and Eq using it and used Vec.retain() when I inserted data

Ontley
  • 1
  • 5