使用Newtonsoft.Json保存配置时加载失败问题的排查

使用Json来保存一个过滤条件,想着下次软件打开的时候,加载原来的过滤条件。

遇到的问题是,序列化的时候,信息保存下来了,是正常的。

但下次软件重新打开,反序列化的时候,反序列解析结果异常,里面的属性都是null。

先让大家看一下我的配置信息类:

    public class FilterInfo
    {
        public string[] Type { get; internal set; }
        public string[] Protocol { get; internal set; }
        public string[] SourceHardwareAddress { get; internal set; }
        public string[] DestinationHardwareAddress { get; internal set; }
        public string[] SourceAddress { get; internal set; }
        public string[] DestinationAddress { get; internal set; }
        public int[] SourcePort { get; internal set; }
        public int[] DestinationPort { get; internal set; }
        public int[] Length { get; internal set; }
        public int[] PayloadDataLength { get; internal set; }
    }

因为我的属性都是数组,一开始以为数组属性要进行什么定义,不然的反序列化的时候识别不了。查了一下貌似又是不需要的。

还有.NET平台自己的JSON接口试了一下,貌似也是同样的问题。

正在纳闷的时候,订着类又看了一下,才发现修饰符 internal ,恍然大悟,把这个关键去掉以后,果然问题解决了。

    public class FilterInfo
    {
        public string[] Type { get; set; }
        public string[] Protocol { get; set; }
        public string[] SourceHardwareAddress { get; set; }
        public string[] DestinationHardwareAddress { get; set; }
        public string[] SourceAddress { get; set; }
        public string[] DestinationAddress { get; set; }
        public int[] SourcePort { get; set; }
        public int[] DestinationPort { get; set; }
        public int[] Length { get; set; }
        public int[] PayloadDataLength { get; set; }
    }

 

原来每个属性都加上internal是因为都是用VS自动生成的属性。其它的所有操作都是正常的,因为其它的所有操作都是我程序集内部的操作。

活到老,学到老。这么多年一直没遇到这个问题是因为貌似很少用VS去自动生成属性。

因为正好属性又都是数组,一开始也没往internal这块想,成功被带偏。

posted @ 2023-05-19 17:33  wzwyc  阅读(78)  评论(0编辑  收藏  举报