stac/
json.rs

1use crate::{Error, Result};
2use serde::{Serialize, de::DeserializeOwned};
3use std::io::Write;
4
5/// Create a STAC object from JSON.
6pub trait FromJson: DeserializeOwned {
7    /// Creates an object from JSON bytes.
8    ///
9    /// # Examples
10    ///
11    /// ```
12    /// use std::{fs::File, io::Read};
13    /// use stac::{Item, FromJson};
14    ///
15    /// let mut buf = Vec::new();
16    /// File::open("examples/simple-item.json").unwrap().read_to_end(&mut buf).unwrap();
17    /// let item = Item::from_json_slice(&buf).unwrap();
18    /// ```
19    fn from_json_slice(slice: &[u8]) -> Result<Self> {
20        serde_json::from_slice(slice).map_err(Error::from)
21    }
22}
23
24/// Writes a STAC object to JSON bytes.
25pub trait ToJson: Serialize {
26    /// Writes a value as JSON.
27    ///
28    /// # Examples
29    ///
30    /// ```
31    /// use stac::{ToJson, Item};
32    ///
33    /// let mut buf = Vec::new();
34    /// Item::new("an-id").to_json_writer(&mut buf, true).unwrap();
35    /// ```
36    fn to_json_writer(&self, writer: impl Write, pretty: bool) -> Result<()> {
37        if pretty {
38            serde_json::to_writer_pretty(writer, self).map_err(Error::from)
39        } else {
40            serde_json::to_writer(writer, self).map_err(Error::from)
41        }
42    }
43
44    /// Writes a value as JSON bytes.
45    ///
46    /// # Examples
47    ///
48    /// ```
49    /// use stac::{ToJson, Item};
50    ///
51    /// Item::new("an-id").to_json_vec(true).unwrap();
52    /// ```
53    fn to_json_vec(&self, pretty: bool) -> Result<Vec<u8>> {
54        if pretty {
55            serde_json::to_vec_pretty(self).map_err(Error::from)
56        } else {
57            serde_json::to_vec(self).map_err(Error::from)
58        }
59    }
60}
61
62impl<T: DeserializeOwned> FromJson for T {}
63impl<T: Serialize> ToJson for T {}