Last active
August 29, 2015 14:01
-
-
Save mausch/53580e14c2d7eae70163 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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