identity_core/convert/
json.rs

1// Copyright 2020-2022 IOTA Stiftung
2// SPDX-License-Identifier: Apache-2.0
3
4use core::fmt::Formatter;
5
6use serde::Deserialize;
7use serde::Serialize;
8
9use crate::error::Error;
10use crate::error::Result;
11
12/// A convenience-trait for types that can be serialized as JSON.
13pub trait ToJson: Serialize + Sized {
14  /// Serialize `self` as a string of JSON.
15  fn to_json(&self) -> Result<String> {
16    serde_json::to_string(self).map_err(Error::EncodeJSON)
17  }
18
19  /// Serialize `self` as a JSON byte vector.
20  fn to_json_vec(&self) -> Result<Vec<u8>> {
21    serde_json::to_vec(self).map_err(Error::EncodeJSON)
22  }
23
24  /// Serialize `self` as a [`serde_json::Value`].
25  fn to_json_value(&self) -> Result<serde_json::Value> {
26    serde_json::to_value(self).map_err(Error::EncodeJSON)
27  }
28
29  /// Serialize `self` as a pretty-printed string of JSON.
30  fn to_json_pretty(&self) -> Result<String> {
31    serde_json::to_string_pretty(self).map_err(Error::EncodeJSON)
32  }
33}
34
35impl<T> ToJson for T where T: Serialize {}
36
37// =============================================================================
38// =============================================================================
39
40/// A convenience-trait for types that can be deserialized from JSON.
41pub trait FromJson: for<'de> Deserialize<'de> + Sized {
42  /// Deserialize `Self` from a string of JSON text.
43  fn from_json(json: &(impl AsRef<str> + ?Sized)) -> Result<Self> {
44    serde_json::from_str(json.as_ref()).map_err(Error::DecodeJSON)
45  }
46
47  /// Deserialize `Self` from bytes of JSON text.
48  fn from_json_slice(json: &(impl AsRef<[u8]> + ?Sized)) -> Result<Self> {
49    serde_json::from_slice(json.as_ref()).map_err(Error::DecodeJSON)
50  }
51
52  /// Deserialize `Self` from a [`serde_json::Value`].
53  fn from_json_value(json: serde_json::Value) -> Result<Self> {
54    serde_json::from_value(json).map_err(Error::DecodeJSON)
55  }
56}
57
58impl<T> FromJson for T where T: for<'de> Deserialize<'de> + Sized {}
59
60// =============================================================================
61// =============================================================================
62
63/// A convenience-trait to format types as JSON strings for display.
64pub trait FmtJson: ToJson {
65  /// Format this as a JSON string or pretty-JSON string based on whether the `#` format flag
66  /// was used.
67  fn fmt_json(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
68    if f.alternate() {
69      f.write_str(&self.to_json_pretty().map_err(|_| core::fmt::Error)?)
70    } else {
71      f.write_str(&self.to_json().map_err(|_| core::fmt::Error)?)
72    }
73  }
74}
75
76impl<T> FmtJson for T where T: ToJson {}