Skip to content

Instantly share code, notes, and snippets.

@computermouth
Created June 1, 2023 20:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save computermouth/833a518e59e23c244794d9de519eab16 to your computer and use it in GitHub Desktop.
Save computermouth/833a518e59e23c244794d9de519eab16 to your computer and use it in GitHub Desktop.
use serde::{Serialize, Deserialize};
use serde::de::{Deserializer, SeqAccess, Visitor};
use std::fmt;
#[derive(Debug)]
struct BatchAction {}
#[derive(Serialize, Deserialize, Debug)]
struct KVItem<'a> {
key: &'a str,
value: &'a str,
time_to_live_sec: Option<usize>,
metadata: Option<&'a str>,
background_fetch: Option<bool>
}
fn main() -> std::io::Result<()> {
let out = r#"
[
{
"key": "key1",
"value": "value1"
},
{
"key": "key2",
"value": "value2",
"time_to_live_sec":60
},
{
"key": "key3",
"value": "value3",
"time_to_live_sec":60,
"metadata":"Up to 2000B of data"
},
{
"key": "key4",
"value": "value4",
"time_to_live_sec":60,
"metadata":"Up to 2000B of data",
"background_fetch":true
},
{
"key":
},
{
"key": "key5"
},
{
"value": "value4"
},
{
"key": "key6",
"value": "value6"
},
]
"#;
let mut de = serde_json::Deserializer::from_str(&out);
let thing = de.deserialize_seq(BatchAction{});
println!("action: {:?}", thing);
Ok(())
}
fn print_type_of<T>(_: &T) {
println!("{}", std::any::type_name::<T>())
}
impl<'de> Visitor<'de> for BatchAction
{
type Value = bool;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("array of items")
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
loop {
match seq.next_element::<KVItem>() {
Ok(o) => {
match o {
Some(s) => println!("{:?}", s),
None => break,
}
}
Err(e) => {
print_type_of(&e);
println!("{:?}", e)
}
}
}
Ok(true)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment