温馨提示×

C#中变量的XML与JSON序列化怎么实现

小亿
87
2024-05-06 16:13:59
栏目: 编程语言

在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格式的数据。可以根据需要对代码进行调整以满足特定的序列化需求。

0