using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Collections.ObjectModel;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
public abstract class Base
[Newtonsoft.Json.JsonIgnore]
public abstract IComparable SortValue { get; }
public class Derived : Base
public int VoteCount { get; set; }
public override IComparable SortValue => VoteCount;
public static void Test()
var derived = new Derived { VoteCount = 101 };
var json1 = Newtonsoft.Json.JsonConvert.SerializeObject(derived);
Console.WriteLine(json1);
var json2 = DataContractJsonSerializerHelper.ToContractJson(derived);
Console.WriteLine(json2);
public static partial class DataContractJsonSerializerHelper
private static MemoryStream GenerateStreamFromString(string value)
return new MemoryStream(Encoding.UTF8.GetBytes(value ?? ""));
public static string ToContractJson<T>(this T obj, DataContractJsonSerializer serializer = null)
serializer = serializer ?? new DataContractJsonSerializer(obj == null ? typeof(T) : obj.GetType());
using (var memory = new MemoryStream())
serializer.WriteObject(memory, obj);
memory.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(memory))
return reader.ReadToEnd();
public static T FromContractJson<T>(string json, DataContractJsonSerializer serializer = null)
serializer = serializer ?? new DataContractJsonSerializer(typeof(T));
using (var stream = GenerateStreamFromString(json))
var obj = serializer.ReadObject(stream);
public static void Main()
Console.WriteLine("Environment version: {0} ({1})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , GetNetCoreVersion());
Console.WriteLine("Failed with unhandled exception: ");
public static string GetNetCoreVersion()
var assembly = typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly;
var assemblyPath = assembly.CodeBase.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
return assemblyPath[netCoreAppIndex + 1];