JSON参数解析工具类

/// <summary>
    /// 解析JSON参数
    /// </summary>
    public class JSONParser
    {
        JObject jObj = null;

        public JSONParser(string param)
        {
            try
            {
                jObj = JObject.Parse(param);
            }
            catch (Exception ex)
            {
                LoggerHelper.Info("JSONParser Init Error:param = {0},{1}", param, ex);
                jObj = null;
            }
        }

        /// <summary>
        /// 获取string类型
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public string GetString(string name)
        {
            if (jObj == null || jObj[name] == null)
            {
                return "";
            }

            try
            {
                return ((JValue)jObj[name]).Value.ToString();
            }
            catch (Exception ex)
            {
                LoggerHelper.Info("JSONParser GetString Error:name = {0},{1}", name, ex);
                return "";
            }
        }

        /// <summary>
        /// 获取JSON值
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public T Get<T>(string name)
        {
            if (jObj == null || jObj[name] == null)
            {
                return default(T);
            }

            try
            {
                return (T)Convert.ChangeType(((JValue)jObj[name]).Value.ToString(), typeof(T));
            }
            catch (Exception ex)
            {
                LoggerHelper.Info("JSONParser Get Error:name = {0},{1}", name, ex);
                return default(T);
            }
        }
    }

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。