.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 小时前
【Redis分布式锁】高并发场景下秒杀业务的实现思路(集群模式)
java·数据库·redis·分布式·后端·spring·
盖世英雄酱581361 小时前
InnoDB 的页分裂和页合并
数据库·后端
小_太_阳1 小时前
Scala_【2】变量和数据类型
开发语言·后端·scala·intellij-idea
直裾2 小时前
scala借阅图书保存记录(三)
开发语言·后端·scala
星就前端叭2 小时前
【开源】一款基于Vue3 + WebRTC + Node + SRS + FFmpeg搭建的直播间项目
前端·后端·开源·webrtc
小林coding3 小时前
阿里云 Java 后端一面,什么难度?
java·后端·mysql·spring·阿里云
AI理性派思考者3 小时前
【保姆教程】手把手教你在Linux系统搭建早期alpha项目cysic的验证者&证明者
后端·github·gpu
从善若水4 小时前
【2024】Merry Christmas!一起用Rust绘制一颗圣诞树吧
开发语言·后端·rust
机器之心4 小时前
终于等来能塞进手机的文生图模型!十分之一体量,SnapGen实现百分百的效果
人工智能·后端
机器之心4 小时前
首次!大模型自动搜索人工生命,做出AI科学家的Sakana AI又放大招
人工智能·后端