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

如何用IDistributedCache缓存数组?反序列化失败求助

分布式缓存反序列化数组类型失败问题

我有一个基于ASP.NET Core 6框架的C#项目,需要使用IDistributedCache缓存AppraisalResult[]类型的数据。编写的AppraisalCacheService类中,StoreAsync方法运行正常,但尝试将缓存值转换回AppraisalResult[]时失败,报错:

{"Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'AppraisalResult[]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.\r\nPath '0'."}

更新内容

尝试在反序列化前读取缓存时也出现错误,代码如下:

var data = await _distributedCache.GetAsync(key);

if (data != null)
{
    using MemoryStream ms = new MemoryStream(data);
    using BsonDataReader reader = new BsonDataReader(ms);
    var dd = reader.ReadAsBytes(); 
}

执行reader.ReadAsBytes()时抛出异常:

{"Error reading bytes. Unexpected token: StartObject. Path '0'."}

报错信息中文翻译

  1. 反序列化失败报错:

无法将当前JSON对象(例如{"name":"value"})反序列化为类型AppraisalResult[],因为该类型需要JSON数组(例如[1,2,3])才能正确反序列化。
要修复此错误,请将JSON改为JSON数组格式,或者修改反序列化的目标类型,使其成为可从JSON对象反序列化的普通.NET类型(比如不是整数这类基元类型,也不是数组、List这类集合类型)。也可以给目标类型添加JsonObjectAttribute特性,强制其从JSON对象反序列化。
路径:0。

  1. 读取缓存时的报错:

读取字节时出错。意外令牌:StartObject。路径:0。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 20:05:17