【发布时间】:2020-07-26 23:43:46
【问题描述】:
我刚刚从 2.2 迁移到 ASP.NET Core 3.1,我收到了这个错误:
System.NotSupportedException: The collection type 'System.Collections.Generic.Dictionary`2[System.Object,System.Object]' is not supported.
at System.Text.Json.JsonClassInfo.GetElementType(Type propertyType, Type parentType, MemberInfo memberInfo, JsonSerializerOptions options)
at System.Text.Json.JsonClassInfo.CreateProperty(Type declaredPropertyType, Type runtimePropertyType, Type implementedPropertyType, PropertyInfo propertyInfo, Type parentClassType, JsonConverter converter, JsonSerializerOptions options)
at System.Text.Json.JsonClassInfo.AddProperty(Type propertyType, PropertyInfo propertyInfo, Type classType, JsonSerializerOptions options)
at System.Text.Json.JsonClassInfo.AddPolicyProperty(Type propertyType, JsonSerializerOptions options)
at System.Text.Json.JsonClassInfo..ctor(Type type, JsonSerializerOptions options)
at System.Text.Json.JsonSerializerOptions.GetOrAddClass(Type classType)
at System.Text.Json.WriteStackFrame.Initialize(Type type, JsonSerializerOptions options)
at System.Text.Json.JsonSerializer.WriteAsyncCore(Stream utf8Json, Object value, Type inputType, JsonSerializerOptions options, CancellationToken cancellationToken)
at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
但是,我安装了这个包Microsoft.AspNetCore.Mvc.NewtonsoftJson,还在启动中添加了services.AddControllers().AddNewtonsoftJson()
那么为什么仍然忽略 Newtonsoft 而使用 System.Text.Json 呢?
编辑: 代码抛出错误:
public async Task<Dictionary<object, object>> GetTemplatesDictAsync(
int? from = 0,
int? take = 100,
string search = null)
{
var _templates = await _repository.GetAllAsync(from, take, search, );
var _dict = _templates.ToDictionary(t => (object)t.id, t => (object)t);
// also append a property with original list
_dict.Add("list", _templates);
return _dict;
}
注意:我将 Dictionary<object, object> 更改为 Dictionary<string, object> 并且代码有效。不过,问题是为什么不使用 Newtonsoft.Json。
EDIT2:
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentications(Configuration);
services.AddAutoMapping();
services.AddMemoryCache();
services.AddOData();
// 3.1:
services.AddControllers()
.AddNewtonsoftJson()
;
// used in 2.2:
// var mvcCoreBuilder = services.AddMvcCore();
// mvcCoreBuilder
// .AddFormatterMappings()
// .AddJsonFormatters()
谢谢
【问题讨论】:
-
你的 startup.cs 是什么样的?
-
请参阅Edit2。谢谢
标签: c# json asp.net-core json.net