我正在研究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
});
但是,它不起作用:items集合通过其声明的类型(IMyInterface)而不是实际的类型进行序列化。我阅读了here,这是预期的行为,尽管对我而言不是那么直观。
我的问题是:[即使有匿名对象,也有任何便捷而可靠的方法来利用新的序列化程序吗?我避免每次可以内联编写结果时都创建一个特定的对象。
更新:
这样做似乎很奏效,但是看起来确实很丑陋:
return new ActionResult<object>(new
{
totalCount,
min,
max,
items = items.Cast<object>()
});
如果要序列化对象,为什么不将它们初始化为对象?是否需要创建强类型?
public static void Test()
{
var items = new List<object>() { new Class1 { Foo = "foo1", Bar1 = "Bar1" }, new Class2 { Foo = "foo1", Bar2 = "Bar2" } };
int totalCount = 1;
int min = 2;
int max = 3;
var root = new
{
totalCount,
min,
max,
items,
};
var json = JsonSerializer.Serialize<object>(root, new JsonSerializerOptions { WriteIndented = true, });
Console.WriteLine(json);
}
如果将项目创建为List<object>
,则无需更改或执行任何操作。这可能是一种更清洁的方法,而不是在创建对象时将它们每个都强制转换为对象。