Function serde_json_any_key::json_to_iter

source ·
pub fn json_to_iter<K, V>(
    str: &str,
) -> Result<impl Iterator<Item = Result<(K, V), Error>>, Error>
where for<'de> K: Deserialize<'de> + Any, for<'de> V: Deserialize<'de>,
Expand description

Reverses to_json_map(), returning an Iterator<Item=Result<(K,V), serde_json::Error>>.

Note that because JSON deserialization may fail for any individual element of the map, you will need to check for errors with each element returned from the iterator.

§Examples

use std::collections::{BTreeMap, HashMap};
use serde::{Serialize, Deserialize};
use serde_json::Error;
use serde_json_any_key::*;
 
#[derive(Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, Ord, PartialOrd)]
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 ser = map.to_json_map().unwrap();
 
// Contruct any type of collection using from_iter(), collect(), or extend()
let deser1: HashMap<Test, Test> = HashMap::from_iter(json_to_iter::<Test,Test>(&ser).unwrap().map(|x| x.unwrap()));
assert_eq!(map, deser1);
 
let deser2: BTreeMap<Test, Test> = json_to_iter::<Test,Test>(&ser).unwrap().map(|x| x.unwrap()).collect();
 
let mut deser3: Vec<(Test, Test)> = Vec::new();
deser3.extend(json_to_iter::<Test,Test>(&ser).unwrap().map(|x| x.unwrap()));
Ok(()) }
try_main().unwrap();