using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Collections.ObjectModel;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
public class SuppressCollectionTypeNamesContractResolver : DefaultContractResolver
internal static TypeNameHandling? RemoveCollectionTypenameHandling(TypeNameHandling? typeNameHandling, Type valueType)
=> typeNameHandling ?? (typeof(IEnumerable).IsAssignableFrom(valueType) && valueType != typeof(string) ? TypeNameHandling.None : typeNameHandling);
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
var property = base.CreateProperty(member, memberSerialization);
property.TypeNameHandling = RemoveCollectionTypenameHandling(property.TypeNameHandling, property.PropertyType);
protected override JsonArrayContract CreateArrayContract(Type objectType)
var contract = base.CreateArrayContract(objectType);
contract.ItemTypeNameHandling = RemoveCollectionTypenameHandling(contract.ItemTypeNameHandling, contract.CollectionItemType);
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; }
public static void Test()
var result = new DataSourceResult
Data = new List<Model> { new (), new () },
Groups = new List<List<object>> { new () { new Model () }, new () { new Model (), new object() } },
var resolver = new SuppressCollectionTypeNamesContractResolver();
var settings = new JsonSerializerSettings
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
ContractResolver = resolver,
TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto,
var json = JsonConvert.SerializeObject(result, Formatting.Indented, settings);
Assert.IsTrue(json.Contains("$type"));
Assert.IsFalse(json.Contains("$values"));
public static void Main()
Console.WriteLine("Environment version: {0} ({1})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , GetNetCoreVersion());
Console.WriteLine("{0} version: {1}", typeof(JsonSerializer).Assembly.GetName().Name, typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine("Failed with unhandled exception: ");
public static string GetNetCoreVersion()
var assembly = typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly;
var assemblyPath = assembly.Location.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
return assemblyPath[netCoreAppIndex + 1];