baichun-framework-core 0.1.0

Core module for Baichun-Rust framework
Documentation
use serde::{de::DeserializeOwned, Serialize};

use crate::error::{Error, Result};

/// JSON工具
pub struct JsonUtils;

impl JsonUtils {
    /// 对象转JSON字符串
    pub fn to_string<T: Serialize>(value: &T) -> Result<String> {
        serde_json::to_string(value).map_err(Error::from)
    }

    /// 对象转美化的JSON字符串
    pub fn to_string_pretty<T: Serialize>(value: &T) -> Result<String> {
        serde_json::to_string_pretty(value).map_err(Error::from)
    }

    /// JSON字符串转对象
    pub fn from_str<T: DeserializeOwned>(s: &str) -> Result<T> {
        serde_json::from_str(s).map_err(Error::from)
    }

    /// 对象转JSON值
    pub fn to_value<T: Serialize>(value: &T) -> Result<serde_json::Value> {
        serde_json::to_value(value).map_err(Error::from)
    }

    /// JSON值转对象
    pub fn from_value<T: DeserializeOwned>(value: serde_json::Value) -> Result<T> {
        serde_json::from_value(value).map_err(Error::from)
    }

    /// 合并两个JSON对象
    pub fn merge(value1: &mut serde_json::Value, value2: serde_json::Value) -> Result<()> {
        match (value1, value2) {
            (a @ &mut serde_json::Value::Object(_), serde_json::Value::Object(b)) => {
                if let serde_json::Value::Object(a) = a {
                    for (k, v) in b {
                        if !a.contains_key(&k) {
                            a.insert(k, v);
                        }
                    }
                }
                Ok(())
            }
            _ => Err(Error::System("只能合并两个JSON对象".to_string())),
        }
    }

    /// 检查字符串是否为有效的JSON
    pub fn is_valid(s: &str) -> bool {
        serde_json::from_str::<serde_json::Value>(s).is_ok()
    }
}