发布于 2026-01-06 4 阅读
0

C# 中的序列化和反序列化:综合指南

C# 中的序列化和反序列化:综合指南

序列化反序列化是软件开发中的基础过程,它们能够将复杂的数据结构转换为适合存储或传输的格式。在 C# 中,这通常涉及使用 JSON(JavaScript 对象表示法),一种轻量级的数据交换格式。

序列化:

序列化是将对象或数据结构转换为易于存储或传输的格式的过程。在 C# 中,由于其简单性和广泛的支持,JSON 序列化被广泛使用。C System.Text.Json# 中的命名空间为序列化提供了一种强大的机制。

以下是将 C# 动态对象序列化为 JSON 字符串的示例:

using System.Text.Json;

class Program
{
    static void Main()
    {
        // Create a dynamic object
        dynamic person = new 
{ 
          Name = "John Doe",
         Age = 30,
          IsActive = true
 };

        // Serialize the dynamic object to a JSON string
        string jsonString = JsonConvert.Serialize(person);

        // Display the serialized JSON string
        Console.WriteLine(jsonString);
    }
}

Enter fullscreen mode Exit fullscreen mode

序列化

在这个例子中,我们创建了一个代表人的动态对象。JsonSerializer.Serialize然后使用该方法将此对象转换为 JSON 格式的字符串。

反序列化:

反序列化是将序列化字符串转换回对象的逆过程。该JsonSerializer.Deserialize方法用于此目的。

using System.Text.Json;

class Program
{
    static void Main()
    {
        // A JSON string representing a person
        string jsonString = "{\"Name\":\"John Doe\",\"Age\":30,\"IsActive\":true}";

        // Deserialize the JSON string into a dynamic object
        dynamic deserializedPerson = JsonConvert.DeserializeObject<dynamic>(jsonString);

        // Accessing properties of the deserialized dynamic object
        string name = deserializedPerson.Name;
        int age = deserializedPerson.Age;
        bool isActive = deserializedPerson.IsActive;

        // Displaying deserialized data
        Console.WriteLine($"Name: {name}, Age: {age}, IsActive: {isActive}");
    }
}

Enter fullscreen mode Exit fullscreen mode

反序列化

在这个例子中,一个表示人员的 JSON 字符串被反序列化回一个动态对象。该JsonSerializer.Deserialize方法与 type 参数一起使用,以处理对象的动态特性。

将 JSON序列化反序列化为 C# 动态对象,为处理数据结构提供了极大的灵活性,尤其是在处理动态或未知模式时。然而,必须妥善处理潜在的异常,并确保在反序列化过程中 JSON 结构与预期的对象属性保持一致。

Web 服务中序列化和反序列化的重要性

序列化反序列化在Web服务中扮演着至关重要的角色,它们促进了客户端和服务器之间高效的数据交换。理解这些过程对于构建可扩展且可互操作的Web应用程序至关重要。

1. 数据传输:
Web 服务通常涉及不同组件(例如客户端和服务器)之间的数据交换。序列化将复杂的数据结构转换为易于通过网络传输的格式(例如 JSON 或 XML)。

// Serialization for a web service request
string requestBody = JsonSerializer.Serialize(requestObject);
Enter fullscreen mode Exit fullscreen mode

让我们扩展一下代码示例,提供一个更详细的流程:

using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        // Assume we have a request object
        var requestObject = new RequestModel
        {
            Name = "John Doe",
            Age = 30,
            IsActive = true
        };

        // Serialize the request object to JSON
        string requestBody = JsonSerializer.Serialize(requestObject);

        // Create a HttpClient for making a web service request
        using (var httpClient = new HttpClient())
        {
            // Define the web service endpoint URL
            string serviceUrl = "https://api.example.com/users";

            // Create a StringContent with the serialized JSON as the request body
            StringContent content = new StringContent(requestBody, Encoding.UTF8, "application/json");

            // Make a POST request to the web service with the serialized JSON in the request body
            HttpResponseMessage response = await httpClient.PostAsync(serviceUrl, content);

            // Check if the request was successful
            if (response.IsSuccessStatusCode)
            {
                // Deserialize the response body (assuming it's JSON) into a response object
                string responseBody = await response.Content.ReadAsStringAsync();
                var responseObject = JsonSerializer.Deserialize<ResponseModel>(responseBody);

                // Process the response object as needed
                Console.WriteLine($"Response Received: {responseObject.Message}");
            }
            else
            {
                // Handle the error if the request was not successful
                Console.WriteLine($"Error: {response.StatusCode} - {response.ReasonPhrase}");
            }
        }
    }
}

// Assume we have the following models for request and response
public class RequestModel
{
    public string Name { get; set; }
    public int Age { get; set; }
    public bool IsActive { get; set; }
}

public class ResponseModel
{
    public string Message { get; set; }
}

Enter fullscreen mode Exit fullscreen mode

数据传输

2.互操作性:

Web 服务可以使用不同的技术开发,也可以在各种平台上运行。序列化为数据表示提供了一种标准化的格式,确保了使用不同语言或框架的系统之间的互操作性。

// JSON serialization for interoperability
string jsonData = JsonSerializer.Serialize(dataObject);

Enter fullscreen mode Exit fullscreen mode

让我们进一步展开代码示例,并提供一个流程图来解释请求正文行在确保互操作性方面的作用:

using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        // Assume we have a data object
        var dataObject = new DataModel
        {
            Property1 = "Value1",
            Property2 = 42,
            Property3 = true
        };

        // Serialize the data object to JSON for interoperability
        string jsonData = JsonSerializer.Serialize(dataObject);

        // Create a HttpClient for making a web service request
        using (var httpClient = new HttpClient())
        {
            // Define the web service endpoint URL
            string serviceUrl = "https://api.example.com/data";

            // Create a StringContent with the serialized JSON as the request body
            StringContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");

            // Make a POST request to the web service with the serialized JSON in the request body
            HttpResponseMessage response = await httpClient.PostAsync(serviceUrl, content);

            // Check if the request was successful
            if (response.IsSuccessStatusCode)
            {
                // Deserialize the response body (assuming it's JSON) into a response object
                string responseBody = await response.Content.ReadAsStringAsync();
                var responseObject = JsonSerializer.Deserialize<ResponseModel>(responseBody);

                // Process the response object as needed
                Console.WriteLine($"Response Received: {responseObject.Message}");
            }
            else
            {
                // Handle the error if the request was not successful
                Console.WriteLine($"Error: {response.StatusCode} - {response.ReasonPhrase}");
            }
        }
    }
}

// Assume we have the following models for data and response
public class DataModel
{
    public string Property1 { get; set; }
    public int Property2 { get; set; }
    public bool Property3 { get; set; }
}

public class ResponseModel
{
    public string Message { get; set; }
}

Enter fullscreen mode Exit fullscreen mode

3. 无状态性:
许多 Web 服务都遵循 REST 架构风格,这种风格强调无状态性。序列化允许在通信过程中保留状态信息。而反序列化则会在接收端重建对象。

// Deserialization for processing a web service response
ResponseObject responseObject = JsonSerializer.Deserialize<ResponseObject>(responseBody);

Enter fullscreen mode Exit fullscreen mode

让我们进一步扩展代码示例,以说明反序列化过程以及 responseObject 行如何融入整个流程:

using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        // Assume we have a web service response body (JSON)
        string responseBody = "{\"Message\":\"Data processed successfully\"}";

        // Deserialize the response body into a ResponseModel object
        ResponseModel responseObject = JsonSerializer.Deserialize<ResponseModel>(responseBody);

        // Process the deserialized response object
        Console.WriteLine($"Response Message: {responseObject.Message}");
    }
}

// Assume we have the following model for the response
public class ResponseModel
{
    public string Message { get; set; }
}

Enter fullscreen mode Exit fullscreen mode

4. 高效的数据存储:

序列化数据通常存储在数据库中或通过网络连接传输。它减少了复杂数据结构带来的开销,并优化了存储和带宽使用。

// Serialization for storing data in a database
string serializedData = JsonSerializer.Serialize(databaseObject);

Enter fullscreen mode Exit fullscreen mode

让我们在代码示例的基础上,提供更详细的数据序列化和数据库存储流程:

using System;
using System.Text.Json;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        // Assume we have an object representing data to be stored in a database
        var databaseObject = new DatabaseModel
        {
            RecordId = 1,
            Data = "Serialized data for storage",
            Timestamp = DateTime.Now
        };

        // Serialize the data object for storage in a database
        string serializedData = JsonSerializer.Serialize(databaseObject);

        // Simulate storing the serialized data in a SQL Server database
        StoreSerializedDataInDatabase(serializedData);
    }

    static void StoreSerializedDataInDatabase(string dataToStore)
    {
        // Assuming a connection string to a SQL Server database
        string connectionString = "your_connection_string_here";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();

            // Assuming a table named 'SerializedData' with columns 'Id' and 'SerializedData'
            string insertQuery = "INSERT INTO SerializedData (SerializedData) VALUES (@SerializedData)";

            using (SqlCommand command = new SqlCommand(insertQuery, connection))
            {
                // Add parameters to the SQL query
                command.Parameters.AddWithValue("@SerializedData", dataToStore);

                // Execute the SQL command to insert the serialized data into the database
                command.ExecuteNonQuery();
            }
        }

        Console.WriteLine("Serialized data successfully stored in the database.");
    }
}

// Assume we have the following model for the database
public class DatabaseModel
{
    public int RecordId { get; set; }
    public string Data { get; set; }
    public DateTime Timestamp { get; set; }
}

Enter fullscreen mode Exit fullscreen mode

5. API 集成:
在微服务架构中,各种服务需要无缝通信。序列化和反序列化确保数据能够在微服务之间高效传递,从而实现内聚集成。

// JSON serialization for communication between microservices
string requestData = JsonSerializer.Serialize(requestObject);

Enter fullscreen mode Exit fullscreen mode

让我们进一步扩展代码示例,以说明 JSON 序列化如何促进微服务之间的通信:

using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        // Assume we have a request object for microservice communication
        var requestObject = new MicroserviceRequest
        {
            MicroserviceId = 1,
            Data = "Request data for microservice communication"
        };

        // Serialize the request object for communication between microservices
        string requestData = JsonSerializer.Serialize(requestObject);

        // Simulate making a request to another microservice
        await MakeMicroserviceRequest(requestData);
    }

    static async Task MakeMicroserviceRequest(string requestData)
    {
        // Assume the URL of another microservice
        string microserviceUrl = "https://microservice.example.com/api/data";

        // Create a HttpClient for making the microservice request
        using (var httpClient = new HttpClient())
        {
            // Create a StringContent with the serialized JSON as the request body
            StringContent content = new StringContent(requestData, Encoding.UTF8, "application/json");

            // Make a POST request to the microservice with the serialized JSON in the request body
            HttpResponseMessage response = await httpClient.PostAsync(microserviceUrl, content);

            // Check if the request was successful
            if (response.IsSuccessStatusCode)
            {
                // Deserialize the response body (assuming it's JSON) into a response object
                string responseBody = await response.Content.ReadAsStringAsync();
                var responseObject = JsonSerializer.Deserialize<MicroserviceResponse>(responseBody);

                // Process the response object as needed
                Console.WriteLine($"Response Received from Microservice: {responseObject.Message}");
            }
            else
            {
                // Handle the error if the request was not successful
                Console.WriteLine($"Error: {response.StatusCode} - {response.ReasonPhrase}");
            }
        }
    }
}

// Assume we have the following models for microservice request and response
public class MicroserviceRequest
{
    public int MicroserviceId { get; set; }
    public string Data { get; set; }
}

public class MicroserviceResponse
{
    public string Message { get; set; }
}

Enter fullscreen mode Exit fullscreen mode

6. 版本控制和兼容性:

随着 Web 服务的演进,数据结构可能会发生变化。序列化通过实现向前和向后兼容来支持版本控制,确保新旧服务版本之间能够有效通信。

// Deserialization with versioning support
ResponseObject responseObject = JsonSerializer.Deserialize<ResponseObject>(responseBody);

Enter fullscreen mode Exit fullscreen mode

让我们扩展一下代码示例,来演示如何实现支持版本控制的反序列化:

using System;
using System.Text.Json;

class Program
{
    static void Main()
    {
        // Assume we have a web service response body with versioned data (JSON)
        string responseBody = "{\"Message\":\"Data processed successfully\",\"Version\":\"2.0\"}";

        // Deserialize the response body with versioning support into a ResponseModel object
        ResponseModel responseObject = DeserializeWithVersioning<ResponseModel>(responseBody);

        // Process the deserialized response object
        Console.WriteLine($"Response Message: {responseObject.Message}");
        Console.WriteLine($"Response Version: {responseObject.Version}");
    }

    static T DeserializeWithVersioning<T>(string json)
    {
        // Configure JsonSerializerOptions with versioning support
        var options = new JsonSerializerOptions
        {
            // Specify the version handling policy (can be Skip, Allow, or ReadAhead)
            DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingDefault,
            ReadCommentHandling = JsonCommentHandling.Skip,
            DefaultBufferSize = 256,
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
            PropertyNameCaseInsensitive = true,
            DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
            AllowTrailingCommas = true,
            WriteIndented = true,
            Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
            DefaultBufferSize = 1024,
            IgnoreNullValues = false,
            MaxDepth = 64,
            ReadBufferSize = 1024
        };

        // Deserialize the JSON with versioning support
        return JsonSerializer.Deserialize<T>(json, options);
    }
}

// Assume we have the following model for the response with versioning
public class ResponseModel
{
    public string Message { get; set; }
    public string Version { get; set; }
}

Enter fullscreen mode Exit fullscreen mode

序列化和反序列化是 Web 服务的基础流程,它们确保数据无缝交换,促进互操作性,并支持现代 Web 应用程序所需的可扩展性和效率。对于任何从事 Web 服务开发的人员来说,理解这些流程都至关重要。

LinkedIn AccountLinkedInTwitter图片来源
Twitter AccountMorioh

文章来源:https://dev.to/iamcymentho/serialization-and-deserialization-in-ca-compressive-guide-5bj9