remoc/codec/
json.rs

1use serde::{Deserialize, Serialize};
2
3use super::{Codec, DeserializationError, SerializationError};
4
5/// JSON codec.
6///
7/// See [serde_json] for details.
8///
9/// When using this with data the contains maps with non-string keys you will
10/// need to apply attributes from [map](super::map) to work correctly.
11#[cfg_attr(docsrs, doc(cfg(feature = "codec-json")))]
12#[derive(Clone, Serialize, Deserialize)]
13pub struct Json;
14
15impl Codec for Json {
16    fn serialize<Writer, Item>(writer: Writer, item: &Item) -> Result<(), super::SerializationError>
17    where
18        Writer: std::io::Write,
19        Item: serde::Serialize,
20    {
21        serde_json::to_writer(writer, item).map_err(SerializationError::new)
22    }
23
24    fn deserialize<Reader, Item>(reader: Reader) -> Result<Item, super::DeserializationError>
25    where
26        Reader: std::io::Read,
27        Item: serde::de::DeserializeOwned,
28    {
29        serde_json::from_reader(reader).map_err(DeserializationError::new)
30    }
31}