.net core 中的序列化和反序列化
时间: 2023-10-30 07:08:30 浏览: 61
在 .NET Core 中,我们可以使用以下两种方式进行对象序列化和反序列化:
1. BinaryFormatter:BinaryFormatter 是 .NET Framework 中常用的一种序列化方式,它可以将对象序列化为二进制格式,也可以将二进制格式反序列化为对象。在 .NET Core 中,BinaryFormatter 仍然可以使用,但是需要注意的是,它只支持 .NET Framework 中的类型,不支持 .NET Core 中新增的类型。
以下是使用 BinaryFormatter 进行序列化和反序列化的示例代码:
```csharp
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public class Program
{
public static void Main()
{
// 创建一个 Person 对象
var person = new Person { Name = "Tom", Age = 30 };
// 将 Person 对象序列化为 byte[]
var formatter = new BinaryFormatter();
using (var stream = new MemoryStream())
{
formatter.Serialize(stream, person);
var bytes = stream.ToArray();
}
// 将 byte[] 反序列化为 Person 对象
using (var stream = new MemoryStream(bytes))
{
var p = (Person)formatter.Deserialize(stream);
Console.WriteLine($"Name: {p.Name}, Age: {p.Age}");
}
}
}
```
2. Newtonsoft.Json:Newtonsoft.Json 是一个流行的 JSON 序列化/反序列化库,它支持 .NET Core 中的所有类型,并且性能也非常不错。我们可以通过 NuGet 引用 Newtonsoft.Json 库,并使用 JsonConvert 类进行序列化和反序列化。
以下是使用 Newtonsoft.Json 进行序列化和反序列化的示例代码:
```csharp
using System;
using Newtonsoft.Json;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public class Program
{
public static void Main()
{
// 创建一个 Person 对象
var person = new Person { Name = "Tom", Age = 30 };
// 将 Person 对象序列化为 JSON 字符串
var json = JsonConvert.SerializeObject(person);
Console.WriteLine(json);
// 将 JSON 字符串反序列化为 Person 对象
var p = JsonConvert.DeserializeObject<Person>(json);
Console.WriteLine($"Name: {p.Name}, Age: {p.Age}");
}
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)