My issue is that I need some $type on my serialized json, I have some subclasses and it's very useful for me.
This is my startup
services.AddTransient<Microsoft.Extensions.Options.IConfigureOptions<Microsoft.AspNetCore.Mvc.MvcNewtonsoftJsonOptions>, App_Start.MvcJsonOptionsSetup>();
services.AddControllers()
.AddNewtonsoftJson()
.SetCompatibilityVersion(CompatibilityVersion.Latest)
.AddControllersAsServices();
internal class MvcJsonOptionsSetup : IConfigureOptions<MvcNewtonsoftJsonOptions>
{
private readonly IHttpContextAccessor _provider;
public MvcJsonOptionsSetup(IHttpContextAccessor provider)
{
}
public MvcJsonOptionsSetup(IHttpContextAccessor provider)
{
_provider = provider;
}
public Func<IServiceProvider> GetProvider()
{
return () => _provider.HttpContext?.RequestServices;
}
public override void Configure(MvcNewtonsoftJsonOptions options)
{
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
options.SerializerSettings.ConfigureRepositoryForJson<EntidadeBase>(GetProvider());
options.SerializerSettings.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto;
}
}
The problem is with the arrays; I would like to never put the $values, but sometimes the return type is not the same.
Did anyone make some extension that would be TypeNAmeHandling.Auto except for arrays?
For example, I use the kendo grid, and the return is this:
{
"Data": {
"$type": "System.Collections.Generic.List`1[[Model.Entity, Model]], System.Private.CoreLib",
"$values": [
...
]
},
"Groups": null,
"Aggregates": null,
"Total": 4,
"Errors": null
}
And I would like it as this
{
"Data": [
...
]
,
"Groups": null,
"Aggregates": null,
"Total": 4,
"Errors": null
}
I'm not using the
TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Objects
to make the result even simpler, I would like to return only if the type is a subclass.
This is the result class
public class DataSourceResult
{
public IEnumerable Data { get; set; }
public IEnumerable Groups { get; set; }
public object Aggregates { get; set; }
public int Total { get; set; }
public object Errors { get; set; }
}
Finally, note that I can't put attributes (such as [JsonProperty(TypeNameHandling=TypeNameHandling.None)]) in all classes, I mean, there are libraries that I use and can't change, I was looking for something that I could override the newtonsoft serializer and check if was array and ignore the typeNamehandling property.