using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
public static class JsonExtensions
const string valuesName = "$values";
const string typeName = "$type";
public static JToken RemoveTypeMetadata(this JToken root)
throw new ArgumentNullException();
var types = root.SelectTokens(".." + typeName).Select(v => (JProperty)v.Parent).ToList();
foreach (var typeProperty in types)
var parent = (JObject)typeProperty.Parent;
var valueProperty = parent.Property(valuesName);
if (valueProperty != null && parent.Count == 1)
var value = valueProperty.Value;
valueProperty.Value = null;
if (parent.Parent != null)
public int Bar { get; set; }
public static void Test()
foreach (var json in GetJson())
Console.WriteLine("\nInput JSON: ");
var newJson = JToken.Parse(json).RemoveTypeMetadata();
Console.WriteLine("Cleaned JSON: ");
Console.WriteLine(newJson);
Assert.IsTrue(!newJson.ToString().Contains("$type"));
Console.WriteLine("\nDone.");
static string[] GetJson()
var settings = new JsonSerializerSettings
TypeNameHandling = TypeNameHandling.All,
""$type"": ""ConsoleAppCompare.Movie, ConsoleAppCompare"",
""$type"": ""ConsoleAppCompare.Character[], ConsoleAppCompare"",
""$type"": ""ConsoleAppCompare.Character, ConsoleAppCompare"",
""Name"": ""Phil Coulson""
""$type"": ""ConsoleAppCompare.Character, ConsoleAppCompare"",
""$type"": ""ConsoleAppCompare.Character[], ConsoleAppCompare"",
""$type"": ""ConsoleAppCompare.Character, ConsoleAppCompare"",
""Name"": ""Phil Coulson""
""$type"": ""ConsoleAppCompare.Character, ConsoleAppCompare"",
JsonConvert.SerializeObject(Enumerable.Range(0, 2).Select(i => Enumerable.Range(0, 2).Select(j => Enumerable.Range(0, 2).Select(k => new Foo { Bar = k }).ToList()).ToArray()).ToList(), settings),
public static void Main()
Console.WriteLine("Environment version: " + Environment.Version);
Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine("Failed with unhandled exception: ");
public class AssertionFailedException : System.Exception
public AssertionFailedException() : base() { }
public AssertionFailedException(string s) : base(s) { }
public static class Assert
public static void IsTrue(bool value)
public static void IsTrue(bool value, string message)
throw new AssertionFailedException(message ?? "failed");