对象和XML,JSON格式字符串的相互转换

前端之家收集整理的这篇文章主要介绍了对象和XML,JSON格式字符串的相互转换前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  • 对象和Json格式数据互转。这里用到了JSON.NET(Newtonsoft.json)需要应用外部dll,可自行下载
            /// <summary>
            /// 把对象序列化 JSON 字符串 
            /// </summary>
            /// <typeparam name="T">对象类型</typeparam>
            /// <param name="obj">对象实体</param>
            /// <returns>JSON字符串</returns>
            public static string ToJsonString<T>(this T obj)
            {
                var json = new DataContractJsonSerializer(typeof(T));
                using (var ms = new MemoryStream())
                {
                    json.WriteObject(ms,obj);
                    string szJson = Encoding.UTF8.GetString(ms.ToArray());
                    return szJson;
                }
            }
    
            /// <summary>
            /// 把JSON字符串还原为对象
            /// </summary>
            /// <typeparam name="T">对象类型</typeparam>
            /// <param name="szJson">JSON字符串</param>
            /// <returns>对象实体</returns>
            public static T ParseFormJson<T>(this string szJson)
            {
                T obj = Activator.CreateInstance<T>();
                using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
                {
                    var dcj = new DataContractJsonSerializer(typeof(T));
                    return (T)dcj.ReadObject(ms);
                }
            }
  • 对象和xml格式字符串互转。as作用:强制转换为引用类型,所以T要限制为class。
            /// <summary>
            /// 把对象转换为XML字符串
            /// </summary>
            /// <typeparam name="T">对象类型</typeparam>
            /// <param name="obj">对象实体</param>
            /// <returns>xml格式的字符串</returns>
            public static string ToXmlString<T>(this T obj)
            {
                string xmlString;
                var xmlSerializer = new XmlSerializer(typeof(T));
                using (var ms = new MemoryStream())
                {
                    var streamWriter = new StreamWriter(ms);
                    xmlSerializer.Serialize(streamWriter,obj);
    
                    xmlString = Encoding.UTF8.GetString(ms.ToArray());
                }
                return xmlString;
            }
    
            /// <summary>
            /// 把XML格式的字符串还原为对象
            /// </summary>
            /// <typeparam name="T">对象类型</typeparam>
            /// <param name="xml">xml格式字符串</param>
            /// <returns>对象实体</returns>
            public static T XmlToObject<T>(this string xml) where T : class
            {
    
                var xmlSerializer = new XmlSerializer(typeof(T));
                using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
                {
                    return xmlSerializer.Deserialize(ms) as T;
                }
            }
原文链接:https://www.f2er.com/xml/296374.html

猜你在找的XML相关文章