在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
處理這些情況。