Json数据序列化对象,及对象序列化为Json格式

public class JsonHelper
    {
        /// <summary>
        /// 生成Json格式
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string GetJson<T>(T obj)
        {
            DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType());
            using (MemoryStream stream = new MemoryStream())
            {
                json.WriteObject(stream, obj);
                string szJson = Encoding.UTF8.GetString(stream.ToArray());
                return szJson;
            }
        }
        /// <summary>
        /// 转换Json的Model对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="szJson"></param>
        /// <returns></returns>
        public static T ParseFromJson<T>(string szJson)
        {
            T obj = Activator.CreateInstance<T>();
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                return (T)serializer.ReadObject(ms);
            }
        }
        /// <summary>
        /// 根据Json获取Dictionary集合
        /// </summary>
        /// <param name="szJson"></param>
        /// <returns></returns>
        public static Dictionary<string, string> GetDictionaryFromJson(string szJson)
        {
            Dictionary<string, string> list = new Dictionary<string, string>();

            System.Web.Script.Serialization.JavaScriptSerializer jsonConvert = new System.Web.Script.Serialization.JavaScriptSerializer();
            list = jsonConvert.Deserialize<Dictionary<string, string>>(szJson);

            return list;
        }
    }

 

Json数据序列化对象,及对象序列化为Json格式,古老的榕树,5-wow.com

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