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);
            }
        }
    }

 

posted @ 2015-03-12 22:49  flysoul  阅读(791)  评论(0编辑  收藏  举报