rocketmq_common/utils/
serde_json_utils.rs

1/*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements.  See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18pub struct SerdeJsonUtils;
19
20impl SerdeJsonUtils {
21    /// Deserialize JSON from bytes into a Rust type.
22    /// Alias for `from_json_slice` for backward compatibility.
23    #[inline]
24    pub fn from_json_bytes<T>(bytes: &[u8]) -> rocketmq_error::RocketMQResult<T>
25    where
26        T: serde::de::DeserializeOwned,
27    {
28        Self::from_json_slice(bytes)
29    }
30
31    /// Deserialize JSON from bytes into a Rust type.
32    #[deprecated(
33        since = "0.7.0",
34        note = "Use `from_json_bytes` or `from_json_slice` instead"
35    )]
36    #[inline]
37    pub fn decode<T>(bytes: &[u8]) -> rocketmq_error::RocketMQResult<T>
38    where
39        T: serde::de::DeserializeOwned,
40    {
41        Self::from_json_bytes(bytes)
42    }
43
44    /// Deserialize JSON from a string into a Rust type.
45    #[inline]
46    pub fn from_json_str<T>(json: &str) -> rocketmq_error::RocketMQResult<T>
47    where
48        T: serde::de::DeserializeOwned,
49    {
50        Ok(serde_json::from_str(json)?)
51    }
52
53    /// Deserialize JSON from a byte slice into a Rust type.
54    #[inline]
55    pub fn from_json_slice<T>(json: &[u8]) -> rocketmq_error::RocketMQResult<T>
56    where
57        T: serde::de::DeserializeOwned,
58    {
59        Ok(serde_json::from_slice(json)?)
60    }
61
62    /// Serialize a Rust type into a JSON string (compact format).
63    #[inline]
64    pub fn serialize_json<T>(value: &T) -> rocketmq_error::RocketMQResult<String>
65    where
66        T: serde::Serialize,
67    {
68        Ok(serde_json::to_string(value)?)
69    }
70
71    /// Serialize a Rust type into a JSON string (pretty-printed format).
72    #[inline]
73    pub fn serialize_json_pretty<T>(value: &T) -> rocketmq_error::RocketMQResult<String>
74    where
75        T: serde::Serialize,
76    {
77        Ok(serde_json::to_string_pretty(value)?)
78    }
79
80    /// Serialize a Rust type into a JSON byte vector (compact format).
81    #[inline]
82    pub fn serialize_json_vec<T>(value: &T) -> rocketmq_error::RocketMQResult<Vec<u8>>
83    where
84        T: serde::Serialize,
85    {
86        Ok(serde_json::to_vec(value)?)
87    }
88
89    /// Serialize a Rust type into a JSON byte vector (pretty-printed format).
90    #[inline]
91    pub fn serialize_json_vec_pretty<T>(value: &T) -> rocketmq_error::RocketMQResult<Vec<u8>>
92    where
93        T: serde::Serialize,
94    {
95        Ok(serde_json::to_vec_pretty(value)?)
96    }
97}
98
99#[cfg(test)]
100mod tests {
101    use serde_json::json;
102    use serde_json::Value;
103
104    use super::*;
105
106    #[test]
107    fn from_json_returns_expected_result() {
108        let json = r#"{"key": "value"}"#;
109        let result: Result<Value, _> = SerdeJsonUtils::from_json_str(json);
110        assert!(result.is_ok());
111    }
112
113    #[test]
114    fn from_json_returns_error_for_invalid_json() {
115        let json = "invalid";
116        let result: Result<Value, _> = SerdeJsonUtils::from_json_str(json);
117        assert!(result.is_err());
118    }
119
120    #[test]
121    fn from_json_slice_returns_expected_result() {
122        let json = r#"{"key": "value"}"#.as_bytes();
123        let result: Result<Value, _> = SerdeJsonUtils::from_json_slice(json);
124        assert!(result.is_ok());
125    }
126
127    #[test]
128    fn from_json_slice_returns_error_for_invalid_json() {
129        let json = "invalid".as_bytes();
130        let result: Result<Value, _> = SerdeJsonUtils::from_json_slice(json);
131        assert!(result.is_err());
132    }
133
134    #[test]
135    fn serialize_json_returns_expected_result() {
136        let value = json!({"key": "value"});
137        let result = SerdeJsonUtils::serialize_json(&value);
138        assert!(result.is_ok());
139    }
140
141    #[test]
142    fn serialize_json_pretty_returns_expected_result() {
143        let value = json!({"key": "value"});
144        let result = SerdeJsonUtils::serialize_json_pretty(&value);
145        assert!(result.is_ok());
146    }
147
148    #[test]
149    fn serialize_json_vec_returns_expected_result() {
150        let value = json!({"key": "value"});
151        let result = SerdeJsonUtils::serialize_json_vec(&value);
152        assert!(result.is_ok());
153    }
154
155    #[test]
156    fn serialize_json_vec_pretty_returns_expected_result() {
157        let value = json!({"key": "value"});
158        let result = SerdeJsonUtils::serialize_json_vec_pretty(&value);
159        assert!(result.is_ok());
160    }
161
162    use std::fmt::Debug;
163
164    use rocketmq_error::RocketMQError;
165    use serde::Deserialize;
166    use serde::Serialize;
167
168    #[derive(Serialize, Deserialize, Debug, PartialEq)]
169    struct TestStruct {
170        name: String,
171        age: u8,
172    }
173
174    #[test]
175    fn test_from_json_success() {
176        let json_str = r#"{"name":"Alice","age":30}"#;
177        let expected = TestStruct {
178            name: "Alice".to_string(),
179            age: 30,
180        };
181        let result: TestStruct = SerdeJsonUtils::from_json_str(json_str).unwrap();
182        assert_eq!(result, expected);
183    }
184
185    #[test]
186    fn test_from_json_error() {
187        let json_str = r#"{"name":"Alice","age":"thirty"}"#;
188        let result: rocketmq_error::RocketMQResult<TestStruct> =
189            SerdeJsonUtils::from_json_str(json_str);
190        assert!(result.is_err());
191    }
192
193    #[test]
194    fn test_from_json_slice_success() {
195        let json_slice = r#"{"name":"Bob","age":25}"#.as_bytes();
196        let expected = TestStruct {
197            name: "Bob".to_string(),
198            age: 25,
199        };
200        let result: TestStruct = SerdeJsonUtils::from_json_slice(json_slice).unwrap();
201        assert_eq!(result, expected);
202    }
203
204    #[test]
205    fn test_from_json_slice_error() {
206        let json_slice = r#"{"name":"Bob","age":"twenty-five"}"#.as_bytes();
207        let result: rocketmq_error::RocketMQResult<TestStruct> =
208            SerdeJsonUtils::from_json_slice(json_slice);
209        assert!(result.is_err());
210    }
211
212    #[test]
213    fn test_serialize_json_success() {
214        let value = TestStruct {
215            name: "Charlie".to_string(),
216            age: 40,
217        };
218        let expected = r#"{"name":"Charlie","age":40}"#;
219        let result: String = SerdeJsonUtils::serialize_json(&value).unwrap();
220        assert_eq!(result, expected);
221    }
222
223    #[test]
224    fn test_serialize_json_error() {
225        // This test is a bit tricky since `serialize_json` should not normally fail
226        // unless there's a bug in `serde_json`. We can't really force an error
227        // in a meaningful way, so we'll just ensure that the method returns a
228        // `Result` and does not panic.
229        let value = TestStruct {
230            name: "Charlie".to_string(),
231            age: 40,
232        };
233        let result: rocketmq_error::RocketMQResult<String> = SerdeJsonUtils::serialize_json(&value);
234        assert!(result.is_ok());
235    }
236}