Skip to content

Instantly share code, notes, and snippets.

@mausch
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mausch/53580e14c2d7eae70163 to your computer and use it in GitHub Desktop.
Save mausch/53580e14c2d7eae70163 to your computer and use it in GitHub Desktop.
using System;
using Newtonsoft.Json;
class Foo {
public override string ToString() {
return "Foo";
}
}
class Bar<T> where T : Foo {
public readonly T foo;
public Bar(T foo) {
this.foo = foo;
}
}
class Baz : Foo {
public override string ToString() {
return "Baz";
}
}
class Program {
static void Main(string[] args) {
var settings = new JsonSerializerSettings {TypeNameHandling = TypeNameHandling.Auto};
var json = JsonConvert.SerializeObject(new Bar<Foo>(new Baz()), settings);
Console.WriteLine(json); // {"foo": {"$type": "Baz, ConsoleApplication13"}}
var bar = JsonConvert.DeserializeObject<Bar<Foo>>(json, settings);
Console.WriteLine(bar.foo.ToString()); // prints "Baz"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment