.NET 序列化的三种方式

参考

C#中Json序列化和反序列化总结

JavaScriptSerialize

创建实体类

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Serializer
{
    public class UserInfo
    {
        /// <summary>
        /// 编号
        /// </summary>
        public int ID { get; set; }

        /// <summary>
        /// 名称
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime? CreateTime { get; set; }


        public UserInfo() { }
        public UserInfo(int id, string name, DateTime? createTime = null)
        {
            this.ID = id;
            this.Name = name;
            this.CreateTime = createTime;
        }
    }
}

测试

ini 复制代码
using Nancy.Json;
using Serializer;

List<UserInfo> userList = new List<UserInfo>();
userList.Add(new UserInfo() { ID = 1, Name = "张三", CreateTime = DateTime.Now });
userList.Add(new UserInfo() { ID = 2, Name = "李四", CreateTime = DateTime.Now });
userList.Add(new UserInfo() { ID = 2, Name = "王五" });

//创建一个JavaScriptSerializer对象
JavaScriptSerializer serializer = new JavaScriptSerializer();

//将用户列表序列化成JSON
string serializedResult = serializer.Serialize(userList);

Console.WriteLine(serializedResult);
//将JOSN反序列化成用户列表
List<UserInfo> deserializeResult = serializer.Deserialize<List<UserInfo>>(serializedResult);
Console.WriteLine(deserializeResult[0].Name);
Console.WriteLine(deserializeResult[0].CreateTime);

Console.ReadLine();

DataContractJsonSerializer

创建实体类

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace DataContractJsonSerializer1
{
    [DataContract]
    public class Order
    {
        private List<OrderItem> items;

        public Order()
        {
        }

        public Order(int id, DateTime orderDate, bool useCoupon)
        {
            this.ID = id;
            this.OrderDate = orderDate;
            this.UseCoupon = useCoupon;
            this.items = new List<OrderItem>();
        }

        [DataMember]
        public int ID { get; set; }

        [DataMember]
        public DateTime OrderDate { get; set; }

        [DataMember]
        public bool UseCoupon { get; set; }

        [DataMember]
        public List<OrderItem> Items
        {
            get { return items; }
            set { items = value; }
        }
    }

    [DataContract]
    public class OrderItem
    {
        public OrderItem(Product product, int count)
        {
            this.Product = product;
            this.Count = count;
        }

        [DataMember]
        public Product Product { get; set; }

        [DataMember]
        public int Count { get; set; }
    }

    [DataContract]
    public class Product
    {
        public Product(string name, double price)
        {
            this.Name = name;
            this.Price = price;
        }

        [DataMember]
        public string Name { get; set; }

        [DataMember]
        public double Price { get; set; }
    }

}

创建工具类

ini 复制代码
using System.Text;
using System.Runtime.Serialization.Json;

namespace DataContractJsonSerializer1
{
    public class JsonHelper
    {
        public static string Serialize<T>(T obj)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
            using (MemoryStream ms = new MemoryStream())
            {
                serializer.WriteObject(ms, obj);
                string retVal = Encoding.UTF8.GetString(ms.ToArray());
                return retVal;
            }
        }

        public static T Deserialize<T>(string json)
        {
            T obj = Activator.CreateInstance<T>();
            MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
            obj = (T)serializer.ReadObject(ms);
            ms.Close();
            ms.Dispose();
            return obj;
        }
    }
}

测试

swift 复制代码
using DataContractJsonSerializer1;
///序列化
Order order = new Order(1, DateTime.Now, true);
order.Items.Add(new OrderItem(new Product("笔记本", 3000), 2));
order.Items.Add(new OrderItem(new Product("无线键鼠", 126.9), 2));
string jsonStr = JsonHelper.Serialize<Order>(order);

Console.WriteLine("\r\n序列化得到Json字符串:\r\n");
Console.WriteLine(jsonStr);

///反序列化
Order dOrder = JsonHelper.Deserialize<Order>(jsonStr);
Console.WriteLine("\r\n\r\n反序列化结果:");
Console.WriteLine("\r\nOrderID: " + dOrder.ID.ToString());
Console.WriteLine("\r\nOrderDate: " + dOrder.OrderDate.ToString("yyyy/MM/dd HH:mm:ss"));
Console.WriteLine("\r\nUseCoupon: " + dOrder.UseCoupon.ToString());

foreach (OrderItem item in dOrder.Items)
{
    Console.WriteLine("\r\n==========================");
    Console.WriteLine("\r\nProduct name: " + item.Product.Name);
    Console.WriteLine("\r\nPrice: " + item.Product.Price.ToString());
    Console.WriteLine("\r\nCount: " + item.Count.ToString());
}

Console.ReadLine();

Newtonsoft.Json

依赖下载

Newtonsoft.Json

测试

//序列化DataTable 复制代码
using Newtonsoft.Json;
using System.Data;

DataTable dt = new DataTable();
dt.Columns.Add("Age", Type.GetType("System.Int32"));
dt.Columns.Add("Name", Type.GetType("System.String"));
dt.Columns.Add("Sex", Type.GetType("System.String"));
dt.Columns.Add("IsMarry", Type.GetType("System.Boolean"));
for (int i = 0; i < 4; i++)
{
    DataRow dr = dt.NewRow();
    dr["Age"] = i + 1;
    dr["Name"] = "Name" + i;
    dr["Sex"] = i % 2 == 0 ? "男" : "女";
    dr["IsMarry"] = i % 2 > 0 ? true : false;
    dt.Rows.Add(dr);
}
string dejsonstr = JsonConvert.SerializeObject(dt);
Console.WriteLine("\r\n序列化得到Json字符串:\r\n");
Console.WriteLine(dejsonstr);


///反序列化           
Console.WriteLine("\r\n\r\n反序列化结果:");
dt = JsonConvert.DeserializeObject<DataTable>(dejsonstr);
foreach (DataRow dr in dt.Rows)
{
    Console.WriteLine("{0}\t{1}\t{2}\t{3}\t", dr[0], dr[1], dr[2], dr[3]);
}

Console.ReadLine();
相关推荐
许野平1 小时前
Rust: 利用 chrono 库实现日期和字符串互相转换
开发语言·后端·rust·字符串·转换·日期·chrono
齐 飞3 小时前
MongoDB笔记01-概念与安装
前端·数据库·笔记·后端·mongodb
LunarCod3 小时前
WorkFlow源码剖析——Communicator之TCPServer(中)
后端·workflow·c/c++·网络框架·源码剖析·高性能高并发
码农派大星。4 小时前
Spring Boot 配置文件
java·spring boot·后端
杜杜的man4 小时前
【go从零单排】go中的结构体struct和method
开发语言·后端·golang
幼儿园老大*4 小时前
走进 Go 语言基础语法
开发语言·后端·学习·golang·go
llllinuuu4 小时前
Go语言结构体、方法与接口
开发语言·后端·golang
cookies_s_s4 小时前
Golang--协程和管道
开发语言·后端·golang
为什么这亚子4 小时前
九、Go语言快速入门之map
运维·开发语言·后端·算法·云原生·golang·云计算
想进大厂的小王5 小时前
项目架构介绍以及Spring cloud、redis、mq 等组件的基本认识
redis·分布式·后端·spring cloud·微服务·架构