System.Json.Net-反序列化Task< T>失败(没有无参数的构造函数) [英] System.Json.Net - deserializing a Task<T> fails (no parameterless constructor)

查看:102
本文介绍了System.Json.Net-反序列化Task< T>失败(没有无参数的构造函数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了无法使用 System.Text.Json (.Net 5)将字符串反序列化为Task的问题.

I'm running into a problem where I can't deserialize a string into a Task using System.Text.Json (.Net 5).

JsonSerializer.Deserialize<Task<TItem>>(serializedItem)

背景

我有一个本地化的缓存,并在其中存储了从数据库中检索到的项目.

Background

I have a localized cache and store in it items retrieved from the DB.

我无法将实际项目存储在缓存中,因为对对象的任何后续操作都会导致对缓存项目进行操作,从而影响所有进一步的使用.因此,我存储了该对象的序列化副本.

I can't store the actual item in the cache, because any subsequent manipulation of the object results in the cached item being manipulation, affecting all further uses. I therefore store a serialized copy of the object.

关于性能...

我正在使用异步/等待模式来调用数据库(整个应用程序都是异步的).

I'm using the async/await pattern to call the DB (the whole app is async).

我读了一篇文章(可能是一段视频),其中斯蒂芬·图卜(Stephen Toub)描述了缓存任务的性能优势.这样的SO文章何时缓存任务?进行了详细介绍.无论如何,我以为我会尝试在本地缓存层"中使用以下代码(无需序列化即可完美工作):

I read an article (may have been a video) in which Stephen Toub described the performance advantage of caching the Task. This SO article When to cache Tasks? goes into the details. Anyhow, I thought I'd try to take advantage of this (it works perfectly without serialization) using the following in my local cache "layer":

  1. 如果Task在我的缓存中,请等待它并返回结果.
  2. 否则,无需等待就调用数据库方法,并将结果任务添加到缓存中

当我添加序列化时,然后反序列化任务:

When I add serialization, then the deserialization of the task:

Task<TItem>? cachedItem = JsonSerializer.Deserialize<Task<TItem>>(serializedItem);

产生

在没有无参数构造函数的情况下对类型进行反序列化单一参数化构造函数,或参数化构造函数不支持带有'JsonConstructorAttribute'注释的

Deserialization of types without a parameterless constructor, a singular parameterized constructor, or a parameterized constructor annotated with 'JsonConstructorAttribute' is not supported.

推荐答案

答案很简单-序列化Task结果中的数据,而不是任务本身.

The answer here is relatively straightforward - serialize the data inside the Task result, not the task itself.

如果您不使用memcached之类的东西,而是使用简单的 Dictionary 进程内对象缓存之类的东西,那么序列化和反序列化似乎是克隆对象的一种繁重方法.

If you aren't using something like memcached but rather using something like a simple Dictionary in-process object cache then serializing and deserializing seems like a rather heavy approach to cloning objects though.

这篇关于System.Json.Net-反序列化Task&lt; T&gt;失败(没有无参数的构造函数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆