重庆熊猫 Loading

.NET教程 - 序列化 & JSON处理 & XML处理(Serialization & JSON & XML)

更新记录
转载请注明出处:
2022年10月1日 发布。
2022年9月29日 从笔记迁移到博客。

XML处理

XML基础

XML介绍

XML指可扩展标记语言(Extensible Markup Language,XML)

XML 被设计用来传输和存储数据

HTML被设计用来显示数据

XML优劣

优点:可读性较好

缺点:文件臃肿

基本语法

头+根

<? xml version="1.0" encoding="utf-8"?>
<root>
     //其他元素
</root>

.NET中处理XML的相关类型

XML相关的类型都在Sysmte.XML命名空间中

类名 描述
XmlDocument 表示一个XML文档的类型
XmlNode 表示一个XML文档中的节点
XmlNodeList 表示一个XML文档中节点的列表
XmlElement 表示一个XML文档中的元素,派生自XmlNode
XmlAttribute 表示一个XML文档中一个元素的属性,派生自XmlNode
XmlText 表示开始标记和结束标记之间的文本
XmlComment 表示一种特殊类型的节点,不是文档的一部分
XmlNodeList 表示一个节点集合
XmlReader 读取XML文档的抽象类
XmlTextReader 读取XML的类型(不检测有效性)
XmlValidatingReader 读取XML的类型(检测有效性)
XmlNodeReader XML DOM读取器
XmlWriter XML写入器的抽象类
XmlTextWriter XML写入器
XmlDataDocument 可执行的XML文档,运行数据通过XML DOM访问
XPathDocument 适合使用XPath导航的XML文档
XPathNavigator 对整个XML文档提供XPath导航
XmlSchema XML Schema
XslTrasform 可执行的转换XML文档的语言

实例

XML文档管理

加载一个XML文档

使用xmlDocument.Load方法

using System;
using System.Xml;

namespace PandaNamespace
{
    public class PandaClass
    {
        public static void Main(string[] args)
        {
            //创建XML文档对象
            XmlDocument xmlDocument = new XmlDocument();
            //加载XML文档
            string filePath = @"D:\test.xml";
            xmlDocument.Load(filePath);

            Console.ReadKey();
        }
    }
}

创建一个XML文档

using System;
using System.Xml;
namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建一个XML文档对象
            XmlDocument xmlDocument = new XmlDocument();

            Console.ReadKey();
        }
    }
}

XML文档保存到文件中

使用xmlDocument.Save方法

using System;
using System.Xml;
namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建一个节点
            XmlElement xmlElement = xmlDocument.CreateElement("PandaCollection");
            
            //XML文档写入到指定文件中
            string path = @"D:/test.xml";
            xmlDocument.Save(path);

            Console.ReadKey();
        }
    }
}

声明节点

创建一个XML声明节点

using System;
using System.Xml;
namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建一个XML文档声明
XmlDeclaration xmlDeclaration = xmlDocument.CreateXmlDeclaration("1.0", "utf-8",null);

            Console.ReadKey();
        }
    }
}

添加声明节点到XML文档

using System;
using System.Xml;
namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建一个XML文档对象
            XmlDocument xmlDocument = new XmlDocument();
            //创建一个XML文档头对象
            XmlDeclaration xmlDeclaration = xmlDocument.CreateXmlDeclaration("1.0", "utf-8",null);
            //添加头对象到XML文档对象中
            xmlDocument.PrependChild(xmlDeclaration);
            Console.ReadKey();
        }
    }
}

从XML文档中移除声明

using System;
using System.Xml;
namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建一个XML文档对象
            XmlDocument xmlDocument = new XmlDocument();
            //创建一个XML文档头对象
            XmlDeclaration xmlDeclaration = xmlDocument.CreateXmlDeclaration("1.0", "utf-8",null);
            //添加头对象到XML文档对象中
            xmlDocument.PrependChild(xmlDeclaration);
			    //移除头节点
            xmlDocument.RemoveChild(xmlDeclaration);

            Console.ReadKey();
        }
    }
}

根节点

添加一个根节点

using System;
using System.Xml;

namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建一个XML文档对象
            XmlDocument xmlDocument = new XmlDocument();
            //创建一个根元素节点
            XmlElement rootNode = xmlDocument.CreateElement("Root");
            //添加到XML文档中
            xmlDocument.AppendChild(rootNode);
            //保存文档
            xmlDocument.Save(@"D:/test.xml");

            Console.ReadKey();
        }
    }
}

获得XML根节点

using System;
using System.Xml;

namespace PandaNamespace
{
    public class PandaClass
    {
        public static void Main(string[] args)
        {
            //创建XML文档对象
            XmlDocument xmlDocument = new XmlDocument();
            //加载XML文档
            string filePath = @"D:\test.xml";
            xmlDocument.Load(filePath);

            //获得根节点
            XmlElement root = xmlDocument.DocumentElement;
            //获得节点的标签名
            Console.WriteLine(root.Name);

            Console.ReadKey();
        }
    }
}

XML节点管理

创建一个节点

using System;
using System.Xml;

namespace PandaNamespace
{
    public class PandaClass
    {
        public static void Main()
        {
            //创建XML文档对象
            XmlDocument xmlDocument = new XmlDocument();
            XmlNode xmlNode = xmlDocument.CreateNode(XmlNodeType.Element, "Panda", null);
            Console.ReadKey();
        }
    }
}

创建一个XML元素节点

using System;
using System.Xml;
namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
XmlDocument xmlDocument = new XmlDocument();

            //创建一个节点
            XmlElement xmlElement = xmlDocument.CreateElement("PandaCollection");


            Console.ReadKey();
        }
    }
}

插入子节点到最前

using System;
using System.Xml;

namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建一个XML文档对象
            XmlDocument xmlDocument = new XmlDocument();
            //创建一个根元素节点
            XmlElement rootNode = xmlDocument.CreateElement("Root");
            //添加到根节点的子节点的最前面
            xmlDocument.PrependChild(rootNode);
            //保存文档
            xmlDocument.Save(@"D:/test.xml");

            Console.ReadKey();
        }
    }
}

插入子节点到最后

using System;
using System.Xml;
namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建一个XML文档对象
            XmlDocument xmlDocument = new XmlDocument();
            
            //创建一个节点
            XmlElement xmlElement = xmlDocument.CreateElement("PandaCollection");
            //添加节点到XML文档最后
            xmlDocument.AppendChild(xmlDocument);
            Console.ReadKey();
        }
    }
}

插入节点到指定节点之后

使用InsertAfter方法

using System;
using System.Xml;

namespace PandaNamespace
{
    public class PandaClass
    {
        public static void Main()
        {
            //创建XML文档对象
            XmlDocument xmlDocument = new XmlDocument();
            //加载XML文档
            string filePath = @"D:\test.xml";
            xmlDocument.Load(filePath);

            //创建元素节点
            XmlElement newNode1 = xmlDocument.CreateElement("newNode1");
            XmlElement newNode2 = xmlDocument.CreateElement("newNode2");
            
            //获得XML文档根节点
            XmlElement root = xmlDocument.DocumentElement;
            //获得XML文档根节点下的第一个节点
            XmlNode firstChildNode = root.FirstChild;

            //插入节点到XML文档的第一个节点之后
            root.InsertAfter(newNode1, firstChildNode);

            //保存文件
            xmlDocument.Save(filePath);

            Console.ReadKey();
        }
    }
}

插入节点到指定节点之前

使用InsertBefore方法

using System;
using System.Xml;

namespace PandaNamespace
{
    public class PandaClass
    {
        public static void Main()
        {
            //创建XML文档对象
            XmlDocument xmlDocument = new XmlDocument();
            //加载XML文档
            string filePath = @"D:\test.xml";
            xmlDocument.Load(filePath);

            //创建元素节点
            XmlElement newNode1 = xmlDocument.CreateElement("newNode1");
            XmlElement newNode2 = xmlDocument.CreateElement("newNode2");
            
            //获得XML文档根节点
            XmlElement root = xmlDocument.DocumentElement;
            //获得XML文档根节点下的第一个节点
            XmlNode firstChildNode = root.FirstChild;

            //插入节点到XML文档的第一个节点之前
            root.InsertBefore(newNode2, firstChildNode);

            //保存文件
            xmlDocument.Save(filePath);

            Console.ReadKey();
        }
    }
}

删除指定子节点

using System;
using System.Xml;

namespace PandaNamespace
{
    public class PandaClass
    {
        public static void Main()
        {
            //创建XML文档对象
            XmlDocument xmlDocument = new XmlDocument();
            //加载XML文档
            string filePath = @"D:\test.xml";
            xmlDocument.Load(filePath);
            
            //获得XML文档根节点
            XmlElement root = xmlDocument.DocumentElement;
            //获得XML文档根节点下的第一个节点
            XmlNode firstChildNode = root.FirstChild;

            //移除第一个节点
            root.RemoveChild(firstChildNode);

            //保存文件
            xmlDocument.Save(filePath);

            Console.ReadKey();
        }
    }
}

删除所有子节点

using System;
using System.Xml;

namespace PandaNamespace
{
    public class PandaClass
    {
        public static void Main()
        {
            //创建XML文档对象
            XmlDocument xmlDocument = new XmlDocument();
            //加载XML文档
            string filePath = @"D:\test.xml";
            xmlDocument.Load(filePath);
            
            //获得XML文档根节点
            XmlElement root = xmlDocument.DocumentElement;
            //获得XML文档根节点下的第一个节点
            XmlNode firstChildNode = root.FirstChild;

            //移除所有子节点
            root.RemoveAll();

            //保存文件
            xmlDocument.Save(filePath);

            Console.ReadKey();
        }
    }
}

替换子节点

using System;
using System.Xml;

namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建一个XML文档对象
            XmlDocument xmlDocument = new XmlDocument();
            //创建一个根元素节点
            XmlElement rootNode = xmlDocument.CreateElement("Root");
            //添加到根节点的子节点的最前面
            xmlDocument.PrependChild(rootNode);
            //创建新元素节点
            XmlElement newElement = xmlDocument.CreateElement("NewRoot");
            //替换子节点
            xmlDocument.ReplaceChild(newElement, rootNode);
            //保存文档
            xmlDocument.Save(@"D:/test.xml");

            Console.ReadKey();
        }
    }
}

XML节点遍历

获得父节点

using System;
using System.Xml;

namespace PandaNamespace
{
    public class PandaClass
    {
        public static void Main(string[] args)
        {
            //创建XML文档对象
            XmlDocument xmlDocument = new XmlDocument();
            //加载XML文档
            string filePath = @"D:\test.xml";
            xmlDocument.Load(filePath);

            //获得根节点
            XmlElement root = xmlDocument.DocumentElement;
            //获得第一个子节点
            XmlNode firstChildNode = root.FirstChild;
            //获得父节点
            XmlNode parentNode = firstChildNode.ParentNode;
            Console.WriteLine(parentNode.Name);

            Console.ReadKey();
        }
    }
}

获得上一个兄弟节点

using System;
using System.Xml;

namespace PandaNamespace
{
    public class PandaClass
    {
        public static void Main(string[] args)
        {
            //创建XML文档对象
            XmlDocument xmlDocument = new XmlDocument();
            //加载XML文档
            string filePath = @"D:\test.xml";
            xmlDocument.Load(filePath);

            //获得根节点
            XmlElement root = xmlDocument.DocumentElement;
            //获得第一个子节点
            XmlNode firstChildNode = root.FirstChild;

            //获得下一个兄弟节点
            XmlNode nextSibling = firstChildNode.NextSibling;
            Console.WriteLine(nextSibling.Name);

            //获得上一个兄弟节点
            XmlNode previousSibling = nextSibling.PreviousSibling;
            Console.WriteLine(previousSibling.Name);

            Console.ReadKey();
        }
    }
}

获得下一个兄弟节点

using System;
using System.Xml;

namespace PandaNamespace
{
    public class PandaClass
    {
        public static void Main(string[] args)
        {
            //创建XML文档对象
            XmlDocument xmlDocument = new XmlDocument();
            //加载XML文档
            string filePath = @"D:\test.xml";
            xmlDocument.Load(filePath);

            //获得根节点
            XmlElement root = xmlDocument.DocumentElement;
            //获得第一个子节点
            XmlNode firstChildNode = root.FirstChild;

            //获得下一个兄弟节点
            XmlNode nextSibling = firstChildNode.NextSibling;
            Console.WriteLine(nextSibling.Name);

            Console.ReadKey();
        }
    }
}

获得节点的第一个子节点

using System;
using System.Xml;

namespace PandaNamespace
{
    public class PandaClass
    {
        public static void Main(string[] args)
        {
            //创建XML文档对象
            XmlDocument xmlDocument = new XmlDocument();
            //加载XML文档
            string filePath = @"D:\test.xml";
            xmlDocument.Load(filePath);

            //获得根节点
            XmlElement root = xmlDocument.DocumentElement;
            //获得第一个子节点
            XmlNode firstChildNode = root.FirstChild;
            //转为XmlElement类型
            XmlElement firstChild = (XmlElement)firstChildNode;
            //获得节点标签名
            Console.WriteLine(firstChild.Name);

            Console.ReadKey();
        }
    }
}

获得节点的最后一个子节点

using System;
using System.Xml;

namespace PandaNamespace
{
    public class PandaClass
    {
        public static void Main(string[] args)
        {
            //创建XML文档对象
            XmlDocument xmlDocument = new XmlDocument();
            //加载XML文档
            string filePath = @"D:\test.xml";
            xmlDocument.Load(filePath);

            //获得根节点
            XmlElement root = xmlDocument.DocumentElement;

            //获得最后一个子节点
            XmlNode lastChildNode = root.LastChild;
            //转为XmlElement类型
            XmlElement lastChild = (XmlElement)lastChildNode;
            //获得节点标签名
            Console.WriteLine(lastChild.Name);

            Console.ReadKey();
        }
    }
}

获得所有子节点

using System;
using System.Xml;

namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建一个XML文档对象
            XmlDocument xmlDocument = new XmlDocument();
            //所有子节点
            XmlNodeList allChildNodes = xmlDocument.ChildNodes;

            Console.ReadKey();
        }
    }
}

检测是否有子节点

using System;
using System.Xml;

namespace PandaNamespace
{
    public class PandaClass
    {
        public static void Main()
        {
            //创建XML文档对象
            XmlDocument xmlDocument = new XmlDocument();
            //加载XML文档
            string filePath = @"D:\test.xml";
            xmlDocument.Load(filePath);

            //获得根节点
            XmlElement root = xmlDocument.DocumentElement;
            if(root.HasChildNodes)
            {
                Console.WriteLine("有子节点");
            }
            else
            {
                Console.WriteLine("没有子节点");
            }

            Console.ReadKey();
        }
    }
}

节点内容管理

获得节点内的所有文本

使用InnerText获得,返回一个字符串,没有XML标记

using System;
using System.Xml;

namespace PandaNamespace
{
    public class PandaClass
    {
        public static void Main()
        {
            //创建XML文档对象
            XmlDocument xmlDocument = new XmlDocument();
            //加载XML文档
            string filePath = @"D:\test.xml";
            xmlDocument.Load(filePath);

            //获得根节点
            XmlElement root = xmlDocument.DocumentElement;

            //获得节点内文本
            Console.WriteLine(root.InnerText);

            Console.ReadKey();
        }
    }
}

设置节点内的文本

使用InnerText设置的文本

注意:如果文本内有<>标签将自动转义,比如:

<PandaTest>&lt;Panda3&gt;Panda3&lt;/Panda3&gt;</PandaTest>

提示:请使用InnerXML来处理XML文档

using System;
using System.Xml;

namespace PandaNamespace
{
    public class PandaClass
    {
        public static void Main()
        {
            //创建XML文档对象
            XmlDocument xmlDocument = new XmlDocument();
            //加载XML文档
            string filePath = @"D:\test.xml";
            xmlDocument.Load(filePath);

            //获得根节点
            XmlElement root = xmlDocument.DocumentElement;

            //设置节点内文本
            root.InnerText = @"Panda3";

            //保存文件
            xmlDocument.Save(filePath);

            Console.ReadKey();
        }
    }
}

获得节点内的所有XML文本

使用InnerXML获得,返回一个字符串,有XML标记

using System;
using System.Xml;

namespace PandaNamespace
{
    public class PandaClass
    {
        public static void Main()
        {
            //创建XML文档对象
            XmlDocument xmlDocument = new XmlDocument();
            //加载XML文档
            string filePath = @"D:\test.xml";
            xmlDocument.Load(filePath);

            //获得根节点
            XmlElement root = xmlDocument.DocumentElement;
            //获得节点内XML文本
            Console.WriteLine(root.InnerXml);

            //保存文件
            xmlDocument.Save(filePath);

            Console.ReadKey();
        }
    }
}

设置节点内的XML文本

注意:如果XML格式错误,将导致程序异常

using System;
using System.Xml;

namespace PandaNamespace
{
    public class PandaClass
    {
        public static void Main()
        {
            //创建XML文档对象
            XmlDocument xmlDocument = new XmlDocument();
            //加载XML文档
            string filePath = @"D:\test.xml";
            xmlDocument.Load(filePath);

            //获得根节点
            XmlElement root = xmlDocument.DocumentElement;

            //设置节点内XML文本
            root.InnerXml = @"<Panda3>Panda3</Panda3><Panda4>Panda4</Panda4>";

            //保存文件
            xmlDocument.Save(filePath);

            Console.ReadKey();
        }
    }
}

读取XML节点的标签名

using System;
using System.Xml;

namespace PandaNamespace
{
    public class PandaClass
    {
        public static void Main(string[] args)
        {
            //创建XML文档对象
            XmlDocument xmlDocument = new XmlDocument();
            //加载XML文档
            string filePath = @"D:\test.xml";
            xmlDocument.Load(filePath);

            //获得根节点
            XmlElement root = xmlDocument.DocumentElement;
            //获得节点的标签名
            Console.WriteLine(root.Name);

            Console.ReadKey();
        }
    }
}

创建一个文本节点

using System;
using System.Xml;

namespace PandaNamespace
{
    public class PandaClass
    {
        public static void Main()
        {
XmlDocument xmlDocument = new XmlDocument();

            //创建一个文本节点
            XmlText xmlText = xmlDocument.CreateTextNode("节点内的文本");

            Console.ReadKey();
        }
    }
}

创建一个注释节点

using System;
using System.Xml;

namespace PandaNamespace
{
    public class PandaClass
    {
        public static void Main()
        {
XmlDocument xmlDocument = new XmlDocument();

            //创建一个注释节点
            XmlComment xmlComment = xmlDocument.CreateComment("注释内容");
            Console.ReadKey();
        }
    }
}

节点属性管理

创建XML节点属性对象

写入XML节点属性1

using System;
using System.Xml;
namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
             XmlDocument xmlDocument = new XmlDocument();

            //创建一个节点
            XmlElement xmlElement = xmlDocument.CreateElement("PandaCollection");
            //给节点写入属性1
            xmlElement.SetAttribute("DateTime", DateTime.Now.ToString());

            Console.ReadKey();
        }
    }
}

写入XML节点属性2

using System;
using System.Xml;
namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建一个节点
            XmlElement xmlElement = xmlDocument.CreateElement("PandaCollection");
            //给节点写入属性2
            //创建XML属性节点
            XmlAttribute xmlAttribute = xmlDocument.CreateAttribute("SomeAttribure");
            xmlAttribute.Value = "666";
            xmlElement.Attributes.Append(xmlAttribute);

            Console.ReadKey();
        }
    }
}

读取XML节点的属性值1

using System;
using System.Xml;
namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建一个节点
            XmlElement xmlElement = xmlDocument.CreateElement("PandaCollection");
            //添加节点的属性
            xmlElement.SetAttribute("Panda", "666");
            //获得指定的属性值
            Console.WriteLine(xmlElement.GetAttribute("Panda"));
            Console.ReadKey();
        }
    }
}

读取XML节点的属性值2

using System;
using System.Xml;
namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建一个节点
            XmlElement xmlElement = xmlDocument.CreateElement("PandaCollection");
            //添加节点的属性
            xmlElement.SetAttribute("Panda", "666");
            //获得指定的属性值
            XmlAttribute xmlAttribute = (XmlAttribute)xmlElement.Attributes.GetNamedItem("Panda");
            Console.WriteLine(xmlAttribute.Value);
            Console.ReadKey();
        }
    }
}

移除XML节点属性1

using System;
using System.Xml;
namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建一个节点
            XmlElement xmlElement = xmlDocument.CreateElement("PandaCollection");
            //添加节点的属性
            xmlElement.SetAttribute("Panda", "666");
            //移除节点的属性
            xmlElement.RemoveAttribute("panda");
            
            Console.ReadKey();
        }
    }
}

移除XML节点属性2

using System;
using System.Xml;
namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建一个节点
            XmlElement xmlElement = xmlDocument.CreateElement("PandaCollection");
            //给节点写入属性2
            //创建XML属性节点
            XmlAttribute xmlAttribute = xmlDocument.CreateAttribute("SomeAttribure");
            xmlAttribute.Value = "666";
            xmlElement.Attributes.Append(xmlAttribute);

            //移除节点的属性
            xmlElement.Attributes.Remove(xmlAttribute);

            Console.ReadKey();
        }
    }
}

统计节点属性的数量

using System;
using System.Xml;
namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建一个节点
            XmlElement xmlElement = xmlDocument.CreateElement("PandaCollection");
            //统计节点属性的数量
            Console.WriteLine(xmlElement.Attributes.Count);

            Console.ReadKey();
        }
    }
}

序列化

.NET中的序列化介绍

序列化基础

序列化(Serialization),也叫串行化
通过将对象转换为字节流,从而存储对象到内存,数据库或文件的过程
主要用途是保存对象的状态数据,以便进行传输和需要时重建对象
对象的状态主要包括字段和属性(不包含方法和事件)

image

反序列化(Deserialization)
将序列化后的数据重新解析成类型的实例

序列化的作用

传递数据
保存数据

.NET中序列化的流程

\1. 将支持序列化的类型进行实例化成对象
\2. 通过使用Formatter/Serializer将被序列化对象进行序列化编码
\3. 然后存入指定的流中
参与序列化过程的对象详细说明:

\1. 被序列化的对象
可以是一个对象,也可是一个集合
需要被序列化的类型需要使用SerializableAttribute 特性修饰
类型中不可序列化的成员需要使用NonSerializedAttribute 特性修饰

\2. 包含已序列化对象的流对象
比如:文件流、内存流

\3. Fromatter/Serializer类型
用于给被序列化的对象进行序列化
序列化和反序列化对象所使用的Fromatter/Serializer主要是以下类型

System.Text.Json.JsonSerializer
System.Xml.Serialization.XmlSerializer
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
System.Runtime.Serialization.DataContractSerializer
System.Runtime.Serialization.Json.DataContractJsonSerializer

序列化常用的底层格式

JSON(JavaScript Object Notation)
比较紧凑,适合用于传输
现在常用于Web传输数据
XML(eXtensible Markup Language)
表示数据更加直观,可读性更好
但也导致容量更大

Binary
在二进制序列化中,所有内容都会被序列化
使用二进制编码来生成精简的序列化
可以用于基于存储或socket的网络流

JSON序列化

使用方法

使用方法相当简单,直接使用JsonSerializer静态类

调用Serialize()静态方法进行序列化

JsonSerializer.Serialize()

调用Deserialize()静态方法进行反序列化

JsonSerializer.Deserialize()

实例:序列化与反序列化

using System;
using System.IO;
using System.Text.Json;

namespace Demo
{
    /// <summary>
    /// 测试使用的类型
    /// </summary>
    [Serializable]
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            //新建类型实例
            Student student = new Student()
            {
                Id = 666,
                Name = "Panda",
                Age = 666666
            };

            //进行序列化
            string serializeString = JsonSerializer.Serialize(student,typeof(Student));
            Console.WriteLine(serializeString);

            //反序列化数据
            Student deserializedData = (Student)JsonSerializer.Deserialize(serializeString, typeof(Student));
            Console.WriteLine(deserializedData.Id);
            Console.WriteLine(deserializedData.Name);
            Console.WriteLine(deserializedData.Age);

            //wait
            Console.WriteLine("Success");
            Console.ReadKey();
        }
    }
}

JSON序列化(数据协定)

使用方法

引入命名空间

using System.Runtime.Serialization.Json;

使用DataContractJsonSerializer类型

DataContractJsonSerializer

实例:序列化数据

using System;
using System.IO;
using System.Runtime.Serialization.Json;

namespace ConsoleApp1
{
    /// <summary>
    /// 测试使用的类型
    /// </summary>
    [Serializable]
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            //新建类型实例
            Student student = new Student()
            {
                Id = 666,
                Name = "Panda",
                Age = 666666
            };

            //序列化数据
            //新建文件流
            string filePath = @"E:\新建文本文档.json";
            using(FileStream fileStream = new FileStream(filePath,FileMode.OpenOrCreate))
            {
                //新建序列化对象
                DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(Student));

                //进行序列化
                dataContractJsonSerializer.WriteObject(fileStream, student);
            }
            
            //wait
            Console.WriteLine("Success");
            Console.ReadKey();
        }
    }
}

实例:反序列化数据

using System;
using System.IO;
using System.Runtime.Serialization.Json;

namespace ConsoleApp1
{
    /// <summary>
    /// 测试使用的类型
    /// </summary>
    [Serializable]
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            //新建类型实例
            Student student = new Student()
            {
                Id = 666,
                Name = "Panda",
                Age = 666666
            };

            //序列化数据
            //新建文件流
            string filePath = @"E:\新建文本文档.json";
            using(FileStream fileStream = new FileStream(filePath,FileMode.OpenOrCreate))
            {
                //新建序列化对象
                DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(Student));

                //进行序列化
                dataContractJsonSerializer.WriteObject(fileStream, student);
            }

            //反序列化数据
            //新建文件流
            using (FileStream fileStream1 = new FileStream(filePath, FileMode.Open))
            {
                //新建序列化对象
                DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(Student));

                //进行反序列化
                Student student1 = (Student)dataContractJsonSerializer.ReadObject(fileStream1);

                //读取反序列化后的对象
                Console.WriteLine($"{student1.Id},{student1.Name},{student1.Age}");
            }
            
            //wait
            Console.WriteLine("Success");
            Console.ReadKey();
        }
    }
}

JSON序列化(Newtonsoft.Json)

使用方法

使用之间需要安装Newtonsoft.Json包

序列化为JSON

using System;
using System.IO;
using System.Collections.Generic;

namespace ConsoleApp6
{
    //测试用的类型
    public class Person
    {
        Person()
        {

        }
        public Person(decimal initialSalary)
        {
            Salary = initialSalary;
        }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime DateOfBirth { get; set; }
        public HashSet<Person> Children { get; set; }
        protected decimal Salary { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            //数据集合
            List<Person> people = new List<Person>
            {
                new Person(30000M) { FirstName = "Alice",LastName = "Smith",
                    DateOfBirth = new DateTime(1974, 3, 14) },
                new Person(40000M) { FirstName = "Bob",LastName = "Jones",
                    DateOfBirth = new DateTime(1969, 11, 23) },
                new Person(20000M) { FirstName = "Charlie",LastName = "Cox",
                    DateOfBirth = new DateTime(1984, 5, 4),
                    Children = new HashSet<Person>
                    {   new Person(0M) { FirstName = "Sally",
                        LastName = "Cox",
                        DateOfBirth = new DateTime(2000, 7, 12) } 
                    }
                }
            };

            string jsonPath = Path.Combine(Environment.CurrentDirectory, "people.json");
            using (StreamWriter jsonStream = File.CreateText(jsonPath))
            {
                //新建序列化工具类型
                var jss = new Newtonsoft.Json.JsonSerializer();
                //进行序列化
                jss.Serialize(jsonStream, people);
            }

            //显示序列化后的内容
            Console.WriteLine(File.ReadAllText(jsonPath));

            //wait
            Console.ReadKey();
        }
    }
}

JSON反序列化

using System;
using System.IO;
using System.Collections.Generic;

namespace ConsoleApp6
{
    //测试用的类型
    public class Person
    {
        Person()
        {

        }
        public Person(decimal initialSalary)
        {
            Salary = initialSalary;
        }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime DateOfBirth { get; set; }
        public HashSet<Person> Children { get; set; }
        protected decimal Salary { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            //数据集合
            List<Person> people = new List<Person>
            {
                new Person(30000M) { FirstName = "Alice",LastName = "Smith",
                    DateOfBirth = new DateTime(1974, 3, 14) },
                new Person(40000M) { FirstName = "Bob",LastName = "Jones",
                    DateOfBirth = new DateTime(1969, 11, 23) },
                new Person(20000M) { FirstName = "Charlie",LastName = "Cox",
                    DateOfBirth = new DateTime(1984, 5, 4),
                    Children = new HashSet<Person>
                    {   new Person(0M) { FirstName = "Sally",
                        LastName = "Cox",
                        DateOfBirth = new DateTime(2000, 7, 12) } 
                    }
                }
            };

            string jsonPath = Path.Combine(Environment.CurrentDirectory, "people.json");
            using (StreamReader jsonStream = File.OpenText(jsonPath))
            {
                //新建序列化工具类型
                var jss = new Newtonsoft.Json.JsonSerializer();
                //进行反序列化
                List<Person> data = (List<Person>)jss.Deserialize(jsonStream, typeof(List<Person>));

                //输出内容
                foreach (var item in data)
                {
                    Console.WriteLine("{0} {1}",item.FirstName + item.LastName, item.DateOfBirth);
                }
            }

            //wait
            Console.ReadKey();
        }
    }
}

XML序列化

使用方法

所在命名空间

using System.Xml.Serialization;

使用XmlSerializer类型

XmlSerializer

注意:该类型只序列化public成员,非公共成员会发生异常
注意:需要被序列化的类型必须有无参数的构造函数

自定义集合类型成员的XML元素名称,使用[XmlArray]特性修改该成员即可

[XmlArray]
[XmlArrayItem]   //注意:修饰在和[XmlArray]同一个成员上

自定义XML元素的名称,使用特性修改成员即可

[XmlRoot("RootName")]   指定根节点标签名称
[XmlElement("EleName")] 指定元素名称

将成员转为XML特性,使用特性即可

[XmlAttribute("AtrrName")]

自定义XML命名空间,使用Namespace成员即可

[XmlRoot("RootName",Namespace = "Panda")]
[XmlAttribute("AtrrName", Namespace = "Panda")]
[XmlElement("EleName", Namespace = "Panda")]

实例:序列化为XML

using System;
using System.IO;
using System.Xml.Serialization;

namespace ConsoleApp1
{
    /// <summary>
    /// 测试使用的类型
    /// </summary>
    [Serializable]
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        [NonSerialized]
        public int Age;
    }

    class Program
    {
        static void Main(string[] args)
        {
            //新建类型实例
            Student student = new Student()
            {
                Id = 666,
                Name = "Panda",
                Age = 666666
            };

            //执行序列化
            //创建文件流
            string filePath = @"E:\xml.xml";
            using(FileStream fileStream = new FileStream(filePath,FileMode.OpenOrCreate))
            {
                //创建XML序列化对象
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(Student));
                //执行序列化
                xmlSerializer.Serialize(fileStream, student);
            }

            //执行反序列化
            //创建文件流
            using(FileStream fileStream1 = new FileStream(filePath,FileMode.Open))
            {
                //创建XML序列化对象
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(Student));

                //执行反序列化
                Student data = (Student)xmlSerializer.Deserialize(fileStream1);

                //输出数据
                Console.WriteLine($"{data.Id},{data.Name},{data.Age}");
            }

            //wait
            Console.WriteLine("Success");
            Console.ReadKey();
        }
    }
}

实例:序列化为XML

using System;
using System.IO;
using System.Collections.Generic;
using System.Xml.Serialization;

namespace ConsoleApp6
{
    //测试用的类型
    public class Person
    {
        public Person()
        {

        }

        public Person(decimal initialSalary)
        {
            Salary = initialSalary;
        }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime DateOfBirth { get; set; }
        public HashSet<Person> Children { get; set; }
        protected decimal Salary { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            //需要被序列化数据集合
            List<Person> people = new List<Person>
            {
                new Person(30000M) { FirstName = "Alice",LastName = "Smith",
                    DateOfBirth = new DateTime(1974, 3, 14) },
                new Person(40000M) { FirstName = "Bob",LastName = "Jones",
                    DateOfBirth = new DateTime(1969, 11, 23) },
                new Person(20000M) { FirstName = "Charlie",LastName = "Cox",
                    DateOfBirth = new DateTime(1984, 5, 4),
                    Children = new HashSet<Person>
                    {   new Person(0M) { FirstName = "Sally",
                        LastName = "Cox",
                        DateOfBirth = new DateTime(2000, 7, 12) }
                    }
                }
            };

            //新建文件流
            //文件保存的位置
            string filePath = @"E:\xml.xml";
            using (FileStream stream = new FileStream(filePath,FileMode.OpenOrCreate))
            {
                //新建序列化对象
                XmlSerializer xs = new XmlSerializer(typeof(List<Person>));

                //序列号集合数据到文件中
                xs.Serialize(stream, people);
            }

            //显示序列化后的内容
            Console.WriteLine(File.ReadAllText(filePath));

            //wait
            Console.ReadKey();
        }
    }
}

实例:XML反序列化

using System;
using System.IO;
using System.Collections.Generic;
using System.Xml.Serialization;

namespace ConsoleApp6
{
    //测试用的类型
    public class Person
    {
        Person()
        {

        }

        public Person(decimal initialSalary)
        {
            Salary = initialSalary;
        }

        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime DateOfBirth { get; set; }
        public HashSet<Person> Children { get; set; }
        protected decimal Salary { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            //文件保存的位置
            string filePath = @"E:\xml.xml";

            using (FileStream xmlLoad = new FileStream(filePath,FileMode.OpenOrCreate))
            {
                //序列化工具类
                XmlSerializer xs = new XmlSerializer(typeof(List<Person>));
                //执行反序列化操作
                var loadedPeople = (List<Person>)xs.Deserialize(xmlLoad);
                //输出数据内容
                foreach (var item in loadedPeople)
                {
                    Console.WriteLine("{0} has {1} children.", item.LastName, item.Children.Count);
                }
            }

            //wait
            Console.ReadKey();
        }
    }
}

实例:自定义XML元素的名称/将成员转为XML特性/自定义XML命名空间

using System;
using System.IO;
using System.Collections.Generic;
using System.Xml.Serialization;

namespace ConsoleApp6
{
    /// <summary>
    /// 测试使用的类型
    /// </summary>
    [Serializable]
    [XmlRoot("PandaRoot", Namespace = "panda666.com")]
    public class Student
    {
        public int Id { get; set; }
        [XmlElement("PandaElement", Namespace = "panda666.com")]
        public string Name { get; set; }
        [XmlAttribute("PandaAttribute", Namespace = "panda666.com")]
        public int Age;
    }

    class Program
    {
        static void Main(string[] args)
        {
            //新建类型实例
            Student student = new Student()
            {
                Id = 666,
                Name = "Panda",
                Age = 666666
            };

            //执行序列化
            //创建文件流
            string filePath = @"E:\xml.xml";
            using (FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate))
            {
                //创建XML序列化对象
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(Student));
                //执行序列化
                xmlSerializer.Serialize(fileStream, student);
            }

            //执行反序列化
            //创建文件流
            using (FileStream fileStream1 = new FileStream(filePath, FileMode.Open))
            {
                //创建XML序列化对象
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(Student));

                //执行反序列化
                Student data = (Student)xmlSerializer.Deserialize(fileStream1);

                //输出数据
                Console.WriteLine($"{data.Id},{data.Name},{data.Age}");
            }
            //wait
            Console.ReadKey();
        }
    }
}

二进制序列化

使用方法

在需要支持序列化的类型上使用[Serializable]特性

[Serializable]

然后引入命名空间

using System.Runtime.Serialization.Formatters.Binary;

然后使用BinaryFormatter类型

BinaryFormatter binaryFormatter = new BinaryFormatter();

标记无需序列化的字段,使用[NonSerialized]特性修饰字段即可

[NonSerialized]

注意:
BinaryFormatter类型在.NET 5中已经被标记为废弃
考虑使用JsonSerializer或XmlSerializer代替BinaryFormatter

实例:二进制序列化

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace ConsoleApp1
{
    /// <summary>
    /// 测试使用的类型
    /// </summary>
    [Serializable]
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            //新建类型实例
            Student student = new Student()
            {
                Id = 666,
                Name = "Panda",
                Age = 666666
            };

            //新建文件流
            string filePath = @"E:\新建文本文档.txt";
            using (FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate))
            {
                //新建二进制序列化对象
                BinaryFormatter binaryFormatter = new BinaryFormatter();

                //进行序列化
                binaryFormatter.Serialize(fileStream, student);
            }

            //wait
            Console.WriteLine("Success");
            Console.ReadKey();
        }
    }
}

实例:二进制反序列化

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace ConsoleApp1
{
    /// <summary>
    /// 测试使用的类型
    /// </summary>
    [Serializable]
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            //新建类型实例
            Student student = new Student()
            {
                Id = 666,
                Name = "Panda",
                Age = 666666
            };

            //新建文件流
            string filePath = @"E:\新建文本文档.txt";
            using (FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate))
            {
                //新建二进制序列化对象
                BinaryFormatter binaryFormatter = new BinaryFormatter();

                //进行序列化
                binaryFormatter.Serialize(fileStream, student);
            }

            //新建文件流
            using(FileStream fileStream1 = new FileStream(filePath,FileMode.Open))
            {
                //新建二进制序列化对象
                BinaryFormatter binaryFormatter = new BinaryFormatter();

                //进行反序列化
                Student student1 = (Student)binaryFormatter.Deserialize(fileStream1);

                //输出反序列化的内容
                Console.WriteLine($"{student1.Id},{student1.Name},{student1.Age}");
            }

            //wait
            Console.WriteLine("Success");
            Console.ReadKey();
        }
    }
}

实例:标记无需序列化

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace ConsoleApp1
{
    /// <summary>
    /// 测试使用的类型
    /// </summary>
    [Serializable]
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        [NonSerialized]
        public int Age;
    }

    class Program
    {
        static void Main(string[] args)
        {
            //新建类型实例
            Student student = new Student()
            {
                Id = 666,
                Name = "Panda",
                Age = 666666
            };

            //新建文件流
            string filePath = @"E:\新建文本文档.txt";
            using (FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate))
            {
                //新建二进制序列化对象
                BinaryFormatter binaryFormatter = new BinaryFormatter();

                //进行序列化
                binaryFormatter.Serialize(fileStream, student);
            }

            //新建文件流
            using (FileStream fileStream1 = new FileStream(filePath, FileMode.Open))
            {
                //新建二进制序列化对象
                BinaryFormatter binaryFormatter = new BinaryFormatter();

                //进行反序列化
                Student student1 = (Student)binaryFormatter.Deserialize(fileStream1);

                //输出反序列化的内容
                Console.WriteLine($"{student1.Id},{student1.Name},{student1.Age}");
            }

            //wait
            Console.WriteLine("Success");
            Console.ReadKey();
        }
    }
}

数据协定类型序列化

数据协定说明

数据协定方式进行序列化和反序列化的优点:

​ 不同的类型之间可以进行序列化和反序列化操作

​ 实现跨网络、跨平台、跨应用进行数据通信

使用方法

基本使用

引入命名空间

using System.Runtime.Serialization;

直接使用DataContractSerializer类型进行序列化操作即可

DataContractSerializer

注意:DataContractSerializer类型底层使用XML格式数据

如果需要在底层使用JSON格式数据,需要使用DataContractJsonSerializer

DataContractJsonSerializer
DataContractJsonSerializer所在命名空间
using System.Runtime.Serialization.Json;

统一数据格式

所在命名空间

using System.Runtime.Serialization;

在需要序列化的类型上使用特性

[DataContract(Name = "PandaItem", Namespace = "panda666.com")]

在需要序列化的类型的成员上使用特性

[DataMember(Name = "PandaName")]

在不需要序列化的成员上使用特性

[IgnoreDataMember]

如需指定成员序列化的顺序,可以使用特性的Order成员

[DataMember(Name = "PandaId",Order = 1)]

保留引用实例

对于多个数据重复引用,可以使用保留引用实例来减少数据的生成量

注意:仅在底层是XML序列化中有效

//新建序列化配置对象
DataContractSerializerSettings settings = new DataContractSerializerSettings();
//开启保留引用实例
settings.PreserveObjectReferences = true;
//新建序列化对象
DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(PandaClass), settings);

实例:序列化数据

using System;
using System.IO;
using System.Runtime.Serialization;

namespace ConsoleApp1
{
    /// <summary>
    /// 测试使用的类型
    /// </summary>
    [Serializable]
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            //新建类型实例
            Student student = new Student()
            {
                Id = 666,
                Name = "Panda",
                Age = 666666
            };

            //序列化数据
            //新建文件流
            string filePath = @"E:\新建文本文档.txt";
            using(FileStream fileStream = new FileStream(filePath,FileMode.OpenOrCreate))
            {
                //新建序列化对象
                DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(Student));

                //进行序列化
                dataContractSerializer.WriteObject(fileStream, student);
            }

            //wait
            Console.WriteLine("Success");
            Console.ReadKey();
        }
    }
}

实例:反序列化数据

using System;
using System.IO;
using System.Runtime.Serialization;

namespace ConsoleApp1
{
    /// <summary>
    /// 测试使用的类型
    /// </summary>
    [Serializable]
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            //新建类型实例
            Student student = new Student()
            {
                Id = 666,
                Name = "Panda",
                Age = 666666
            };

            //序列化数据
            //新建文件流
            string filePath = @"E:\新建文本文档.txt";
            using(FileStream fileStream = new FileStream(filePath,FileMode.OpenOrCreate))
            {
                //新建序列化对象
                DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(Student));

                //进行序列化
                dataContractSerializer.WriteObject(fileStream, student);
            }

            //反序列化数据
            //新建文件流
            using (FileStream fileStream1 = new FileStream(filePath,FileMode.Open))
            {
                //新建序列化对象
                DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(Student));

                //进行反序列化
                Student student1 = (Student)dataContractSerializer.ReadObject(fileStream1);

                //输出反序列化的内容
                Console.WriteLine($"{student1.Id},{student1.Name},{student1.Age}");
            }
            //wait
            Console.WriteLine("Success");
            Console.ReadKey();
        }
    }
}

实例:跨类型进行序列化

using System;
using System.IO;
using System.Runtime.Serialization;

namespace ConsoleApp1
{
    /// <summary>
    /// 测试使用的类型1
    /// </summary>
    [DataContract(Name = "PandaItem", Namespace = "panda666.com")]
    public class PandaClass
    {
        [DataMember(Name = "PandaId")]
        public int Id { get; set; }
        [DataMember(Name = "PandaName")]
        public string Name { get; set; }
        [DataMember(Name = "PandaAge")]
        public int Age { get; set; }
    }

    /// <summary>
    /// 测试使用的类型2
    /// </summary>
    [DataContract(Name = "PandaItem", Namespace = "panda666.com")]
    public class PandaClass2
    {
        [DataMember(Name = "PandaId")]
        public int PandaId { get; set; }
        [DataMember(Name = "PandaName")]
        public string PandaName { get; set; }
        [DataMember(Name = "PandaAge")]
        public int PandaAge { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            //新建类型实例
            PandaClass panda = new PandaClass()
            {
                Id = 666,
                Name = "Panda",
                Age = 666666
            };

            //序列化数据
            //新建文件流
            string filePath = @"E:\新建文本文档.xml";
            using (FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate))
            {
                //新建序列化对象
                DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(PandaClass));

                //进行序列化
                dataContractSerializer.WriteObject(fileStream, panda);
            }

            //反序列化数据
            using(FileStream fileStream1 = new FileStream(filePath,FileMode.Open))
            {
                //新建序列化对象
                DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(PandaClass2));

                //进行反序列化
                PandaClass2 data = (PandaClass2)dataContractSerializer.ReadObject(fileStream1);

                //输出数据
                Console.WriteLine($"{data.PandaId},{data.PandaName},{data.PandaAge}");
            }
            //wait
            Console.WriteLine("Success");
            Console.ReadKey();
        }
    }
}

实例:开启保留引用实例

using System;
using System.IO;
using System.Runtime.Serialization;

namespace ConsoleApp1
{
    /// <summary>
    /// 测试使用的类型1
    /// </summary>
    [DataContract(Name = "PandaItem", Namespace = "panda666.com")]
    public class PandaClass
    {
        [DataMember(Name = "PandaId")]
        public int Id { get; set; }
        [DataMember(Name = "PandaName")]
        public string Name { get; set; }
        [DataMember(Name = "PandaAge")]
        public int Age { get; set; }
    }

    /// <summary>
    /// 测试使用的类型2
    /// </summary>
    [DataContract(Name = "PandaItem", Namespace = "panda666.com")]
    public class PandaClass2
    {
        [DataMember(Name = "PandaId")]
        public int PandaId { get; set; }
        [DataMember(Name = "PandaName")]
        public string PandaName { get; set; }
        [DataMember(Name = "PandaAge")]
        public int PandaAge { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            //新建类型实例
            PandaClass panda = new PandaClass()
            {
                Id = 666,
                Name = "Panda",
                Age = 666666
            };

            //序列化数据
            //新建文件流
            string filePath = @"E:\新建文本文档.xml";
            using (FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate))
            {
                //新建序列化配置对象
                DataContractSerializerSettings settings = new DataContractSerializerSettings();
                //开启保留引用实例
                settings.PreserveObjectReferences = true;

                //新建序列化对象
                DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(PandaClass), settings);

                //进行序列化
                dataContractSerializer.WriteObject(fileStream, panda);
            }

            //反序列化数据
            using (FileStream fileStream1 = new FileStream(filePath, FileMode.Open))
            {
                //新建序列化对象
                DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(PandaClass2));

                //进行反序列化
                PandaClass2 data = (PandaClass2)dataContractSerializer.ReadObject(fileStream1);

                //输出数据
                Console.WriteLine($"{data.PandaId},{data.PandaName},{data.PandaAge}");
            }
            //wait
            Console.WriteLine("Success");
            Console.ReadKey();
        }
    }
}

实例:跨类型进行序列化(底层JSON)

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

namespace ConsoleApp1
{
    /// <summary>
    /// 测试使用的类型1
    /// </summary>
    [DataContract(Name = "PandaItem")]
    public class PandaClass
    {
        [DataMember(Name = "PandaId")]
        public int Id { get; set; }
        [DataMember(Name = "PandaName")]
        public string Name { get; set; }
        [DataMember(Name = "PandaAge")]
        public int Age { get; set; }
    }

    /// <summary>
    /// 测试使用的类型2
    /// </summary>
    [DataContract(Name = "PandaItem")]
    public class PandaClass2
    {
        [DataMember(Name = "PandaId")]
        public int PandaId { get; set; }
        [DataMember(Name = "PandaName")]
        public string PandaName { get; set; }
        [DataMember(Name = "PandaAge")]
        public int PandaAge { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            //新建类型实例
            PandaClass panda = new PandaClass()
            {
                Id = 666,
                Name = "Panda",
                Age = 666666
            };

            //序列化数据
            //新建文件流
            string filePath = @"E:\新建文本文档.json";
            using (FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate))
            {
                //新建序列化对象
                DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(PandaClass));

                //进行序列化
                dataContractJsonSerializer.WriteObject(fileStream, panda);
            }

            
            //反序列化数据
            using (FileStream fileStream1 = new FileStream(filePath, FileMode.Open))
            {
                //新建序列化对象
                DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(PandaClass2));

                //进行反序列化
                PandaClass2 data = (PandaClass2)dataContractJsonSerializer.ReadObject(fileStream1);

                //输出数据
                Console.WriteLine($"{data.PandaId},{data.PandaName},{data.PandaAge}");
            }
            //wait
            Console.WriteLine("Success");
            Console.ReadKey();
        }
    }
}
posted @ 2022-10-01 08:37  重庆熊猫  阅读(150)  评论(0编辑  收藏  举报