How to serialize btreemap with serde_json?

I have BTreeMap of Player structs:

#[derive(sqlx::FromRow, Clone, Serialize, Deserialize, Debug)]
pub struct Player {
    pub id: u64,
    pub name: String,
}

let players_map: BTreeMap<u64, Player> = BTreeMap::new();

When I try to serialize it, I got an error:

error[E0277]: a value of type `Vec<(u64, Player)>` cannot be built from an iterator over elements of type `(std::string::String, Player)`
    --> src\server\mod.rs:163:26
     |
163  |                         .collect::<Vec<(u64, Player)>>();
     |                          ^^^^^^^ value of type `Vec<(u64, Player)>` cannot be built from `std::iter::Iterator<Item=(std::string::String, Player)>`
     |
     = help: the trait `FromIterator<(std::string::String, Player)>` is not implemented for `Vec<(u64, Player)>`

I do serialization like below:

let players = players
	.into_iter()
	.map(|(key, value)| (key.to_string(), value))
	.collect::<Vec<(u64, Player)>>();

message = &serde_json::to_string(&players).unwrap();

Could somebody explain how to correctly serialize btreemap ? I expect something like this as output:

[{1: Player, 2: Player, 3: Player}]

where each Player is serialized object.

Your error has nothing to do with serialization, and you aren't even serializing a BTreeMap. You're trying to serialize a Vec.

The error you're getting is because you're mapping the key type to a string and then telling collect to expect a u64.

serde already implements Serialize for BTreeMap so I'm not sure why you're converting to a Vec first.

4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.