Workaround for \"key must be a string\" error with serde_json. Serialize any HashMap
Also supports deserialization to HashMap
```rust use std::collections::HashMap; use serde::{Serialize, Deserialize}; use serdejsonany_key::*;
pub struct Test { pub a: i32, pub b: i32 }
fn main() {
let mut map = HashMap::
// Fails with error: key must be a string let serialized = serdejson::tostring(&map); match serialized { Ok(serialized) => { println!("{}", serialized); } Err(e) => { println!("Error as expected: {}", e); } }
// Long winded workaround that copies the map
// Prints {"{\"a\":3,\"b\":5}":{"a":7,"b":9}}
let stringmap: HashMap
// Use this crate's utility function - elements are serialized lazily // Same output let serialized = serdejsonanykey::mapto_json(&map).unwrap(); println!("{}", serialized);
// Utility function also exists for vec of tuples // Same output let vec = vec![(Test {a: 3, b: 5}, Test {a: 7, b: 9})]; let serialized = serdejsonanykey::vecto_json(&vec).unwrap(); println!("{}", serialized);
// Also supports any other data type that generates an Iter<&(K,V)> or Iter<(&K, &V)>
// Same output
let mut btree = std::collections::BTreeMap::
// Also supports deserialization, back to HashMap or Vec
let deserializedmap: HashMap
Output:
Error as expected: key must be a string
{"{\"a\":3,\"b\":5}":{"a":7,"b":9}}
{"{\"a\":3,\"b\":5}":{"a":7,"b":9}}
{"{\"a\":3,\"b\":5}":{"a":7,"b":9}}
{"{\"a\":3,\"b\":5}":{"a":7,"b":9}}