junobuild_utils/json.rs
1use serde::{Deserialize, Serialize};
2use serde_json::{from_slice, to_string, to_vec};
3
4/// Decodes JSON data into a Rust struct.
5///
6/// Deserializes a byte slice into the specified type using Serde and `serde_json`.
7/// Supports Juno's extended JSON conventions for IC types such as `Principal`, `u64` (bigint),
8/// and `Vec<u8>` (Uint8Array), which are encoded using `@dfinity/utils` compatible markers.
9///
10/// # Parameters
11/// - `data`: A byte slice (`&[u8]`) containing the JSON-encoded data.
12///
13/// # Returns
14/// - `Ok(T)`: Successfully deserialized data of type `T`.
15/// - `Err(String)`: An error string if deserialization fails.
16///
17/// # Example
18///
19/// ```rust
20/// #[derive(Deserialize)]
21/// struct MyData {
22/// name: String,
23/// }
24///
25/// let data: MyData = decode_json_data(bytes)?;
26/// ```
27pub fn decode_json_data<T: for<'a> Deserialize<'a>>(data: &[u8]) -> Result<T, String> {
28 from_slice::<T>(data).map_err(|e| e.to_string())
29}
30
31/// Encodes a Rust struct into JSON bytes.
32///
33/// Serializes the provided data into a byte vector using Serde and `serde_json`.
34/// Supports Juno's extended JSON conventions for IC types such as `Principal`, `u64` (bigint),
35/// and `Vec<u8>` (Uint8Array), which are encoded using `@dfinity/utils` compatible markers.
36///
37/// # Parameters
38/// - `data`: A reference to the Rust data structure to be serialized.
39///
40/// # Returns
41/// - `Ok(Vec<u8>)`: A byte vector containing the JSON-encoded data.
42/// - `Err(String)`: An error string if serialization fails.
43///
44/// # Example
45///
46/// ```rust
47/// #[derive(Serialize)]
48/// struct MyData {
49/// name: String,
50/// }
51///
52/// let bytes = encode_json_data(&my_data)?;
53/// ```
54pub fn encode_json_data<T: Serialize>(data: &T) -> Result<Vec<u8>, String> {
55 to_vec(data).map_err(|e| e.to_string())
56}
57
58/// Encodes a Rust struct into a JSON string.
59///
60/// Serializes the provided data into a `String` using Serde and `serde_json`.
61/// Supports Juno's extended JSON conventions for IC types such as `Principal`, `u64` (bigint),
62/// and `Vec<u8>` (Uint8Array), which are encoded using `@dfinity/utils` compatible markers.
63///
64/// # Parameters
65/// - `data`: A reference to the Rust data structure to be serialized.
66///
67/// # Returns
68/// - `Ok(String)`: A JSON string containing the serialized data.
69/// - `Err(String)`: An error string if serialization fails.
70///
71/// # Example
72///
73/// ```rust
74/// #[derive(Serialize)]
75/// struct MyData {
76/// name: String,
77/// }
78///
79/// let json = encode_json_data_to_string(&my_data)?;
80/// ```
81pub fn encode_json_data_to_string<T: Serialize>(data: &T) -> Result<String, String> {
82 to_string(data).map_err(|e| e.to_string())
83}