webull_rs/utils/
serialization.rs

1use serde::{Deserialize, Serialize};
2use serde_json::{Value, json};
3use crate::error::{WebullError, WebullResult};
4
5/// Convert a struct to a JSON string.
6pub fn to_json<T>(value: &T) -> WebullResult<String>
7where
8    T: Serialize,
9{
10    serde_json::to_string(value)
11        .map_err(|e| WebullError::SerializationError(e))
12}
13
14/// Convert a JSON string to a struct.
15pub fn from_json<T>(json: &str) -> WebullResult<T>
16where
17    T: for<'de> Deserialize<'de>,
18{
19    serde_json::from_str(json)
20        .map_err(|e| WebullError::SerializationError(e))
21}
22
23/// Convert a struct to a JSON value.
24pub fn to_json_value<T>(value: &T) -> WebullResult<Value>
25where
26    T: Serialize,
27{
28    serde_json::to_value(value)
29        .map_err(|e| WebullError::SerializationError(e))
30}
31
32/// Convert a JSON value to a struct.
33pub fn from_json_value<T>(value: Value) -> WebullResult<T>
34where
35    T: for<'de> Deserialize<'de>,
36{
37    serde_json::from_value(value)
38        .map_err(|e| WebullError::SerializationError(e))
39}
40
41/// Build a JSON object with the given parameters.
42pub fn build_json_object(params: &[(&str, Value)]) -> Value {
43    let mut obj = json!({});
44    
45    for (key, value) in params {
46        obj[key] = value.clone();
47    }
48    
49    obj
50}