.net C# Newtonsoft.Json.JsonConvert.SerializeObject 对object类型序列化数据丢失问题

发布时间 2023-10-25 10:49:15作者: wwr01

先说解决方案:

//using System.Text.Json;
string temp = JsonSerializer.Serialize(model);使用System.Text.Json把对象转成字符串就不会丢失;解析的时候可以使用Newtonsoft.Json.JsonConvert;
直接看代码,问题如下:

 public class SaveSurchargeDto
    {
        public SaveTypeEnum SaveType { get; set; }
        public int TlId { get; set; }
        public AddicostDataDto Data { get; set; } = new AddicostDataDto();
        public Dictionary<string, Dictionary<string, string>> ViewInfo { get; set; }

    }
    #endregion

    public class AddicostDataDto
    {
        /// <summary>
        /// 基础视图
        /// </summary>
        public List<SurchargeDto> SurchargeDtoList { get; set; } = new List<SurchargeDto>();
        /// <summary>
        /// 其他视图 Key:ViewName Vale:视图数据
        /// </summary>
        public Dictionary<string, object> AddicostOtherDataDic { get; set; } = new Dictionary<string, object>();
        public List<SurchargeCostpackDto> CostPacks { get; set; }

        public Dictionary<string, List<string>> BaseColumns { get; set; } = new Dictionary<string, List<string>>();

    }

其中AddicostOtherDataDic是有object类型的;我想把这些数据直接放进redis,但是会出现数据丢失问题;如下图;

 

想要的数据结构如下:

 


之后我想干脆直接把这个对象转成一个大字符串保存进redis就可以了,然后使用Newtonsoft.Json.JsonConvert的序列化和反序列化,当把对象转成字符串的时候就出现了相同的问题,字符串数据中的AddicostOtherDataDic也会变成上面这种情况;最后使用using System.Text.Json把对象转成字符串没有出现问题,转成字符串之后保存redis也没有问题,当需要的时候使用Newtonsoft.Json.JsonConvert把字符串转回对象,问题解决;