温馨提示×

c# javascriptserializer能处理复杂对象吗

c#
小樊
81
2024-11-28 04:33:35
栏目: 编程语言

是的,C# 的 JavaScriptSerializer 类可以处理复杂对象。它可以序列化和反序列化各种类型的对象,包括自定义类、集合、字典等。但是,需要注意的是,JavaScriptSerializer 类已经过时,不再建议使用。作为替代方案,你可以使用 JsonConvert 类,它是 Newtonsoft.Json 库的一部分,功能更强大,而且更易于使用。

以下是一个使用 JavaScriptSerializer 处理复杂对象的示例:

using System;
using System.Web.Script.Serialization;

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Address Address { get; set; }
}

public class Address
{
    public string Street { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string ZipCode { get; set; }
}

class Program
{
    static void Main()
    {
        Person person = new Person
        {
            FirstName = "John",
            LastName = "Doe",
            Address = new Address
            {
                Street = "123 Main St",
                City = "Anytown",
                State = "CA",
                ZipCode = "12345"
            }
        };

        JavaScriptSerializer serializer = new JavaScriptSerializer();
        string json = serializer.Serialize(person);
        Console.WriteLine(json);

        Person deserializedPerson = serializer.Deserialize<Person>(json);
        Console.WriteLine($"FirstName: {deserializedPerson.FirstName}, LastName: {deserializedPerson.LastName}, Address: {deserializedPerson.Address.Street}, {deserializedPerson.Address.City}, {deserializedPerson.Address.State}, {deserializedPerson.Address.ZipCode}");
    }
}

如果你想使用 JsonConvert,首先需要安装 Newtonsoft.Json 库。你可以通过 NuGet 包管理器安装它,或者通过以下命令行安装:

dotnet add package Newtonsoft.Json

然后,你可以使用以下代码序列化和反序列化复杂对象:

using System;
using Newtonsoft.Json;

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Address Address { get; set; }
}

public class Address
{
    public string Street { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string ZipCode { get; set; }
}

class Program
{
    static void Main()
    {
        Person person = new Person
        {
            FirstName = "John",
            LastName = "Doe",
            Address = new Address
            {
                Street = "123 Main St",
                City = "Anytown",
                State = "CA",
                ZipCode = "12345"
            }
        };

        string json = JsonConvert.SerializeObject(person);
        Console.WriteLine(json);

        Person deserializedPerson = JsonConvert.DeserializeObject<Person>(json);
        Console.WriteLine($"FirstName: {deserializedPerson.FirstName}, LastName: {deserializedPerson.LastName}, Address: {deserializedPerson.Address.Street}, {deserializedPerson.Address.City}, {deserializedPerson.Address.State}, {deserializedPerson.Address.ZipCode}");
    }
}

0