是的,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}");
}
}