pub trait ConsumingIterToJson<'a, K, V>: IntoIterator<Item = (K, V)>{
// Provided method
fn into_json_map(self) -> Result<String, Error> { ... }
}
Expand description
Blanket impl into_json_map() for all IntoIterator<Item=(K,V)>
types.
Provided Methods§
sourcefn into_json_map(self) -> Result<String, Error>
fn into_json_map(self) -> Result<String, Error>
Serialize any IntoIterator<(K,V)>
to a JSON map. This includes, but is not limited to, the following example types:
HashMap<K,V>
return type of HashMap<K,V>::into_iter()
Vec<(K,V)>
return type of Vec<(K,V)>::into_iter()
To create the JSON map keys, serde_json::to_string()
will be called on each K element.
This consumes self, and is not compatible with non-consuming iterators, such as those returned by the common
std::collections::Type::iter()
function. For those non-consuming iterators, call to_json_map()
instead:
For Map-like types
For Vec-like types
§Examples
use std::collections::{HashMap, BTreeMap};
use serde::Serialize;
use serde_json::Error;
use serde_json_any_key::*;
#[derive(Clone, Copy, Serialize, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Test {
pub a: i32,
pub b: i32
}
fn try_main() -> Result<(), Error> {
let mut map = HashMap::<Test, Test>::new();
map.insert(Test {a: 3, b: 5}, Test {a: 7, b: 9});
let mut btr = BTreeMap::<Test, Test>::new();
btr.insert(Test {a: 3, b: 5}, Test {a: 7, b: 9});
let mut vec = Vec::<(Test, Test)>::new();
vec.push((Test {a: 3, b: 5}, Test {a: 7, b: 9}));
// Outputs {"{\"a\":3,\"b\":5}":{"a":7,"b":9}}
let ser1 = map.into_json_map().unwrap(); // map.into_iter().into_json_map() is also valid
let ser2 = btr.into_json_map().unwrap(); // btr.into_iter().into_json_map() is also valid
let ser3 = vec.into_json_map().unwrap(); // vec.into_iter().into_json_map() is also valid
// map, btr, and vec have all been consumed.
assert_eq!(ser1, "{\"{\\\"a\\\":3,\\\"b\\\":5}\":{\"a\":7,\"b\":9}}");
assert_eq!(ser1, ser2);
assert_eq!(ser1, ser3);
Ok(()) }
try_main().unwrap();
Object Safety§
This trait is not object safe.