在C#中,要對ArrayList進(jìn)行反序列化,首先需要將序列化的數(shù)據(jù)存儲在一個文件中,例如JSON格式。然后,可以使用System.IO.File
類和Newtonsoft.Json
庫來讀取和解析這個文件,最后將解析后的數(shù)據(jù)轉(zhuǎn)換回ArrayList對象。以下是一個簡單的示例:
Install-Package Newtonsoft.Json
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
using System;
using System.Collections.ArrayList;
using Newtonsoft.Json;
class Program
{
static void Main()
{
ArrayList people = new ArrayList();
people.Add(new Person { Name = "John", Age = 30 });
people.Add(new Person { Name = "Jane", Age = 28 });
string json = JsonConvert.SerializeObject(people);
Console.WriteLine("Serialized ArrayList: " + json);
}
}
using System;
using System.Collections.ArrayList;
using Newtonsoft.Json;
class Program
{
static void Main()
{
string json = "[{\"Name\":\"John\",\"Age\":30},{\"Name\":\"Jane\",\"Age\":28}]"; // 這是從文件或網(wǎng)絡(luò)中讀取的序列化數(shù)據(jù)
ArrayList people = JsonConvert.DeserializeObject<ArrayList>(json);
Console.WriteLine("Deserialized ArrayList:");
foreach (Person person in people)
{
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
}
}
這個示例中,我們首先創(chuàng)建了一個包含兩個Person對象的ArrayList,并將其序列化為JSON字符串。然后,我們將這個JSON字符串反序列化為一個新的ArrayList對象,并輸出其內(nèi)容。