在C#中,可以使用內置的System.Xml.Serialization命名空間和System.Runtime.Serialization.Json命名空間來實現變量的XML和JSON序列化。
首先,我們來看如何實現變量的XML序列化:
using System;
using System.IO;
using System.Xml.Serialization;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
Person person = new Person { Name = "Alice", Age = 30 };
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Person));
using (TextWriter writer = new StreamWriter("person.xml"))
{
xmlSerializer.Serialize(writer, person);
}
}
}
接下來,我們來看如何實現變量的JSON序列化:
using System;
using System.IO;
using System.Runtime.Serialization.Json;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
Person person = new Person { Name = "Alice", Age = 30 };
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Person));
using (MemoryStream stream = new MemoryStream())
{
jsonSerializer.WriteObject(stream, person);
string json = System.Text.Encoding.UTF8.GetString(stream.ToArray());
Console.WriteLine(json);
}
}
}
以上示例演示了如何將Person對象序列化為XML和JSON格式的數據。可以根據需要對代碼進行調整以滿足特定的序列化需求。