c# 类实例序列化反序列化json文件

前言

前段时间使用了net.json保存对象数据。添加完成后,测试发现300多实例数据保存加载json文件,速度比原方式(BinaryFormatter)慢。但是功能加上后也懒再删掉代码了,索性就采用两种方式。怎么说两种方式也比一种多不是?_

net.json详细介绍

1 测试之前需要引用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);
    }
}

2 序列化对象默认情况下只有公共成员,此类没有公共成员。故设置特性[JsonObject(MemberSerialization.Fields)]可序列化所有成员。详细可见MemberSerialization

3 对于Intprt hwnd,标记为[JsonIgnore]表示不进行序列化;当进行反序列化后使用[OnDeserialized]可根据需要重新对其进行赋值 OnDeserializedAttribute 类,对于自定义序列化可参考msdn自定义序列化

测试用例

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(movie2[i].ToString());
    }
}

4 测试代码中集合用ArrayList,故反序列化后需要再次进行转换,把集合里面的每个JObject转换成Student,如果使用List就不需要,如下:

List StuModel = new List()
{
    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)serializer.Deserialize(file, typeof(List));
}

你可能感兴趣的:(C#)