You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET缓存对象时如何忽略NULL属性以节省存储空间?

实现方案

核心思路是在存入缓存前对强类型列表做忽略null属性的序列化处理,仅序列化非null属性后再存入缓存,读取缓存时再反序列化为原类型即可,可大幅降低缓存占用的存储空间。

方案1:使用Newtonsoft.Json(Json.NET)实现

适合所有.NET Framework/.NET Core项目

  • 先安装Newtonsoft.Json NuGet包(已安装可跳过)
  • 存入缓存代码改造:
using Newtonsoft.Json;

// 配置序列化规则:忽略所有null值属性
var serializeSettings = new JsonSerializerSettings
{
    NullValueHandling = NullValueHandling.Ignore
};
// 序列化对象
string serializedData = JsonConvert.SerializeObject(data.Data, serializeSettings);

// 存入缓存
HttpRuntime.Cache.Insert(key, 
   serializedData, 
   null, 
   DateTime.Now.AddMinutes(data.Minutes ?? minutes), 
   TimeSpan.Zero, 
   System.Web.Caching.CacheItemPriority.Default, 
   null);
  • 读取缓存代码:
// 从缓存取数据
string cachedContent = HttpRuntime.Cache.Get(key) as string;
if (!string.IsNullOrEmpty(cachedContent))
{
    // 将T替换为你实际的强类型,列表的话就是List<你的实体类型>
    var result = JsonConvert.DeserializeObject<T>(cachedContent);
}

方案2:使用.NET自带System.Text.Json实现

适合.NET Core 3.0+ / .NET 5+ 版本项目

  • 存入缓存代码改造:
using System.Text.Json;
using System.Text.Json.Serialization;

// 配置序列化规则:忽略所有null值属性
var serializeOptions = new JsonSerializerOptions
{
    DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
// 序列化对象
string serializedData = JsonSerializer.Serialize(data.Data, serializeOptions);

// 存入缓存
HttpRuntime.Cache.Insert(key, 
   serializedData, 
   null, 
   DateTime.Now.AddMinutes(data.Minutes ?? minutes), 
   TimeSpan.Zero, 
   System.Web.Caching.CacheItemPriority.Default, 
   null);
  • 读取缓存代码:
// 从缓存取数据
string cachedContent = HttpRuntime.Cache.Get(key) as string;
if (!string.IsNullOrEmpty(cachedContent))
{
    // 将T替换为你实际的强类型
    var result = JsonSerializer.Deserialize<T>(cachedContent);
}

注意:忽略null属性序列化不会影响业务逻辑,反序列化时未出现在序列化结果中的属性会被自动赋值为对应类型的默认值(引用类型为null、值类型为0/false等),和原对象的属性值完全一致。
如果对缓存空间要求更高,也可以选择MessagePack等二进制序列化框架,同样支持忽略null值配置,序列化后的体积比JSON更小,性能也更高。

内容的提问来源于stack exchange,提问作者Mike Flynn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 20:39:03