1. 程式人生 > >c# 類序列化json檔案

c# 類序列化json檔案

前段時間使用了net.json儲存物件資料。新增完成後,測試發現300多例項資料儲存載入json檔案,速度比原方式(BinaryFormatter)慢。但是功能加上後也懶再刪掉程式碼了,索性就採用兩種方式。怎麼說兩種方式也比一種多不是?^_^

net.json詳細介紹

測試之前需要引用Newtonsoft.Json.dll,可在官網下載最新安裝包。本文寫作時最新Version 10.0.3

測試類Student `

[JsonObject(MemberSerialization.Fields)]
class Student
{
    const int count = 1024;
    public Student(int ID, string Name, int Age, string Sex)
    {
        this.ID = ID;
        this.Name = Name;
        this.Age = Age;
        this.Sex = Sex;

        buffer = new byte[count];
        for (int i = 0; i < count; i++)
        {
            buffer[i] = (byte)i;
        }
    }

    byte[] buffer;

    int ID { get; set; }

    string Name { get; set; }

    int Age { get; set; }

    string Sex { get; set; }

    [JsonIgnore]
    IntPtr hwnd;

    [OnDeserialized]
    private void SetValuesOnDeserialized(StreamingContext context)
    {
        string stringA = "I seem to be turned around!";
        hwnd = System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(stringA);
    }
}

1、序列化物件預設情況下只有公共成員,此類沒有公共成員。故設定特性[JsonObject(MemberSerialization.Fields)]可序列化所有成員。詳細可見MemberSerialization
2、對於Intprt hwnd,標記為[JsonIgnore]表示不進行序列化;當進行反序列化後使用[OnDeserialized]可根據需要重新對其進行賦值 OnDeserializedAttribute 類

測試用例

            ArrayList StuModel = new ArrayList()
            {
                new
Student(1,"王小二",18,"男"), new Student(2,"麗麗",16,"女") }; using (StreamWriter file = File.CreateText(@"test.json")) { JsonSerializer serializer = new JsonSerializer(); serializer.Serialize(file, StuModel); } using
(StreamReader file = File.OpenText(@"test.json")) { JsonSerializer serializer = new JsonSerializer(); var movie2 = (ArrayList)serializer.Deserialize(file, typeof(ArrayList)); for (int i = 0; i < movie2.Count; i++) { movie2[i] = JsonConvert.DeserializeObject<Student>(movie2[i].ToString()); } }

3、測試程式碼中集合用ArrayList,故反序列化後需要再次進行轉換,把集合裡面的每個JObject轉換成Student,如果使用List就不需要。

            List<Student> StuModel = new List<Student>()
            {
                new Student(1,"王小二",18,"男"),
                new Student(2,"麗麗",16,"女")
            };

            using (StreamWriter file = File.CreateText(@"test.json"))
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.Serialize(file, StuModel);
            }

            using (StreamReader file = File.OpenText(@"test.json"))
            {
                JsonSerializer serializer = new JsonSerializer();
                var movie2 = (List<Student>)serializer.Deserialize(file, typeof(List<Student>));
            }

另對於自定義序列化可參考msdn自定義序列化