首页 > Web开发 > 详细

JSON参数解析工具类

时间:2015-03-12 23:55:18      阅读:372      评论:0      收藏:0      [点我收藏+]
/// <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);
            }
        }
    }

 

JSON参数解析工具类

原文:http://www.cnblogs.com/FlySoul/p/4333988.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!