cookbook/
cookbook.rs

1use jsony::{Jsony, RawJson};
2
3/// The `LazyValue` type can be used defer parsing parts
4/// of a payload until later.
5fn deferred_parsing() -> Res<()> {
6    #[derive(Jsony, Debug)]
7    #[jsony(Json)]
8    struct Alpha<'a> {
9        value: &'a str,
10        lazy: &'a RawJson,
11    }
12
13    let input = jsony::object! {
14        value: "Hello",
15        lazy: {
16            key: true,
17            numbers: [1, 2, 3],
18            nested: {
19                data: 42
20            }
21        }
22    };
23
24    let alpha: Alpha = jsony::from_json(&input)?;
25    assert_eq!(alpha.lazy["nested"]["data"].parse::<u32>()?, 42);
26
27    let output = jsony::to_json(&alpha);
28
29    assert_eq!(input, output.as_str());
30
31    Ok(())
32}
33
34fn main() {
35    deferred_parsing().unwrap();
36}
37
38struct Error {
39    location: &'static std::panic::Location<'static>,
40    error: Box<dyn std::error::Error>,
41}
42type Res<T> = Result<T, Error>;
43
44impl std::fmt::Debug for Error {
45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        write!(f, "Failed @ {}: {:?}", self.location, self.error)
47    }
48}
49
50impl<E> From<E> for Error
51where
52    E: Into<Box<dyn std::error::Error>>,
53{
54    #[track_caller]
55    #[inline]
56    fn from(value: E) -> Self {
57        Self {
58            location: std::panic::Location::caller(),
59            error: value.into(),
60        }
61    }
62}