C#微软原生序列化/反序列化类库用法
侧边栏壁纸
  • 累计撰写 62 篇文章
  • 累计收到 23 条评论
C#

C#微软原生序列化/反序列化类库用法

一缕清风
2021-01-16 / 0 评论 / 50 阅读 / 正在检测是否收录...

简介

最近遇到与第三方对接,对方接口接收的是xml格式的报文;而我这边自己平台采用的是json格式的报文;无奈之下只能寻找json与xml共用一个对象序列化/反序列化的办法,以下代码是C#操作xml序列化反序列化以及xml序列化时一些特殊选项设置,例如压缩、编码、命名空间等。

使用教程

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;

namespace TestXml
{
    [XmlRoot("SyncReceiptInfo")]/*xml根节点名称,若类名与节点名一致,则忽略*/
    [Serializable]/*打上此属性表示此对象可被序列化*/
    public class request_instore
    {
         [XmlElement("userId")]/*xml节点名称,字段名与节点名一致,则忽略*/
        public string ownerCode { get; set; }
       

        public string warehouseCode { get; set; }
        

        [XmlElement("sender")]
        public instroe_sender sender { get; set; }

        [XmlArrayItem("item")]/*xml集合中子节点名称*/
        [XmlArray("items")]/*xml集合节点名称*/
        public List<instroe_items> items { get; set; }

    }

    [Serializable]
    public class instroe_sender
    {
        public string name { get; set; }
    }

    [Serializable]
    public class instroe_items
    {
        public string itemSkuCode { get; set; }
        
        public string itemQuantity { get; set; }
        [XmlIgnore]/*打上此属性,表示xml序列化/反序列化将忽略此字段*/
        public string itemEpc { get; set; }
    }

    public class XmlConvert
    {
        /// <summary>
        /// xml序列化
        /// </summary>
        /// <param name="strobj"></param>
        private static string SerializeObject<T>(T obj)
        {
            try
            {
                var _namespace = new XmlSerializerNamespaces();
                _namespace.Add(string.Empty, string.Empty);

                XmlSerializer serializer = new XmlSerializer(obj.GetType());
                var _xmlSetting = new XmlWriterSettings
                {
                    Encoding = Encoding.UTF8,//文本便, 
                    Indent = false, //是否缩进
                    OmitXmlDeclaration = true,//是否省略Xml声明
                    NewLineHandling = NewLineHandling.Replace,//是否压缩
                };


                using (StringWriter _writer = new Utf8StringWriter())
                {
                    using (var _xmlWriter = XmlWriter.Create(_writer, _xmlSetting))
                    {
                        serializer.Serialize(_xmlWriter, obj, _namespace);
                        return _writer.ToString();
                    }
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <returns></returns>
        private static T DeserializeObject<T>(string _xml)
        {
            try
            {
                T obj;
                using (MemoryStream _ms = new MemoryStream(Encoding.UTF8.GetBytes(_xml)))
                {
                    using (XmlReader _reader = XmlReader.Create(_ms))
                    {
                        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
                        obj = (T)xmlSerializer.Deserialize(_reader);
                    }
                }
                return obj;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }

    /// <summary>
    /// XML序列化指定编码类
    /// </summary>
    public class Utf8StringWriter : StringWriter
    {
        public override Encoding Encoding
        {
            get
            {
                return Encoding.UTF8;
            }
        }
    }
}
0

评论 (0)

取消