溫馨提示×

c# arraylist怎樣進行反序列化

c#
小樊
110
2024-11-15 23:53:17
欄目: 編程語言

在C#中,要對ArrayList進行反序列化,首先需要將序列化的數據存儲在一個文件中,例如JSON格式。然后,可以使用System.IO.File類和Newtonsoft.Json庫來讀取和解析這個文件,最后將解析后的數據轉換回ArrayList對象。以下是一個簡單的示例:

  1. 首先,確保已經安裝了Newtonsoft.Json庫。如果沒有安裝,可以使用NuGet包管理器安裝:
Install-Package Newtonsoft.Json
  1. 創建一個簡單的C#類,用于存儲序列化數據:
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}
  1. 使用Newtonsoft.Json庫將ArrayList序列化為JSON字符串:
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);
    }
}
  1. 使用Newtonsoft.Json庫將JSON字符串反序列化為ArrayList對象:
using System;
using System.Collections.ArrayList;
using Newtonsoft.Json;

class Program
{
    static void Main()
    {
        string json = "[{\"Name\":\"John\",\"Age\":30},{\"Name\":\"Jane\",\"Age\":28}]"; // 這是從文件或網絡中讀取的序列化數據

        ArrayList people = JsonConvert.DeserializeObject<ArrayList>(json);

        Console.WriteLine("Deserialized ArrayList:");
        foreach (Person person in people)
        {
            Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
        }
    }
}

這個示例中,我們首先創建了一個包含兩個Person對象的ArrayList,并將其序列化為JSON字符串。然后,我們將這個JSON字符串反序列化為一個新的ArrayList對象,并輸出其內容。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女