c#

C#序列化与反序列化如何处理复杂数据

小樊
90
2024-10-24 10:58:27
栏目: 编程语言

在C#中,处理复杂数据时,可以使用System.Runtime.Serialization命名空间下的类来进行序列化和反序列化。以下是一个简单的示例,展示了如何使用这些类处理包含自定义对象和集合的复杂数据。

首先,创建一个自定义类Person

using System.Runtime.Serialization;

[DataContract]
public class Person
{
    [DataMember]
    public string Name { get; set; }

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

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

[DataContract]
public class Address
{
    [DataMember]
    public string Street { get; set; }

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

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

这里,我们使用[DataContract]属性标记类,以便在序列化和反序列化过程中包含这些类的成员。[DataMember]属性用于指定要序列化和反序列化的成员。

接下来,创建一个包含自定义对象集合的类People

using System.Collections.Generic;
using System.Runtime.Serialization;

[DataContract]
public class People
{
    [DataMember]
    public List<Person> Persons { get; set; }
}

现在,我们可以使用DataContractSerializer类进行序列化和反序列化:

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

class Program
{
    static void Main()
    {
        // 创建一个包含自定义对象集合的实例
        People people = new People
        {
            Persons = new List<Person>
            {
                new Person { Name = "Alice", Age = 30, Address = new Address { Street = "123 Main St", City = "New York", State = "NY" } },
                new Person { Name = "Bob", Age = 25, Address = new Address { Street = "456 Elm St", City = "Los Angeles", State = "CA" } }
            }
        };

        // 序列化对象
        DataContractSerializer serializer = new DataContractSerializer(typeof(People));
        using (StringWriter writer = new StringWriter())
        {
            serializer.WriteObject(writer, people);
            string serializedData = writer.ToString();
            Console.WriteLine("Serialized data:");
            Console.WriteLine(serializedData);
        }

        // 反序列化对象
        using (StringReader reader = new StringReader(serializedData))
        {
            People deserializedPeople = (People)serializer.ReadObject(reader);
            Console.WriteLine("\nDeserialized data:");
            foreach (Person person in deserializedPeople.Persons)
            {
                Console.WriteLine($"Name: {person.Name}, Age: {person.Age}, Address: {person.Address.Street}, {person.Address.City}, {person.Address.State}");
            }
        }
    }
}

这个示例中,我们首先创建了一个包含两个Person对象的People实例。然后,我们使用DataContractSerializer将对象序列化为字符串,再将字符串反序列化为对象。

注意:在实际应用中,你可能需要处理更复杂的数据结构和类型,例如嵌套的对象、集合和字典等。这个示例展示了如何使用DataContractSerializer处理这些情况。

0
看了该问题的人还看了