我正在开发一个 ASP .Net Core 3.1 应用程序,使用 2.2 从另一个应用程序移植部分代码。到目前为止,我想从 NewtonSoft JSON 序列化库切换到新的 System.Text.Json,但遇到了一些麻烦。
考虑一个使用以下返回类型提供 HTTP-GET 服务的函数:
[HttpGet("myservice")]
public async Task<ActionResult<object>> GetDataAsync( ...
那么,最终的部分可以描述如下:
var items = new List<IMyInterface>();
int totalCount = ...
int min = ...
int max = ...
return new ActionResult<object>(new
{
totalCount,
min,
max,
items
});
但是,它不起作用:项目集合按其声明的类型(IMyInterface)而不是实际类型进行序列化。我读here https://stackoverflow.com/questions/58429098/jsonserializer-behaves-not-as-expected-when-the-specifc-class-is-casted-to-somet这是一种预期的行为,尽管对我来说并不那么直观。
我的问题是:是否有任何方便而可靠的方法来利用新的序列化器,甚至处理匿名对象?我会避免每次可以内联组成结果时创建一个特定的对象。
UPDATE:
这样做似乎可行,但看起来真的很难看:
return new ActionResult<object>(new
{
totalCount,
min,
max,
items = items.Cast<object>()
});