欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c# 类实例序列化反序列化json文件 (原发布 csdn 2017-10-01 20:02:12)

程序员文章站 2022-06-19 20:05:08
前言 前段时间使用了net.json保存对象数据。添加完成后,测试发现300多实例数据保存加载json文件,速度比原方式(BinaryFormatter)慢。但是功能加上后也懒再删掉代码了,索性就采用两种方式。怎么说两种方式也比一种多不是?^_^ net.json "详细介绍" 1 测试之前需要引用 ......

前言

前段时间使用了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<student>(movie2[i].tostring());
    }
}

4 测试代码中集合用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>));
}