Skip to content

Instantly share code, notes, and snippets.

@theor
Created October 6, 2014 20:47
Show Gist options
  • Save theor/f68468f93896c832f595 to your computer and use it in GitHub Desktop.
Save theor/f68468f93896c832f595 to your computer and use it in GitHub Desktop.
Json.NET: handling abstract types
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace jsonabstract
{
class Program
{
static void Test<T>(T value)
{
var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects };
Console.WriteLine("Serializing {0}", value);
string json = JsonConvert.SerializeObject(value, settings);
Console.WriteLine(" {0}", json);
T obj = JsonConvert.DeserializeObject<T>(json, settings);
Console.WriteLine(" {0}", obj);
}
static void Main(string[] args)
{
Msg m1 = new MsgA{AProp = "asd", Name = "Msg A"};
Test(m1);
Msg m2 = new MsgB{BProp = 42, Name = "Msg B"};
Test(m2);
Console.ReadLine();
}
}
abstract class Msg { public string Name { get; set; } }
class MsgA : Msg
{
public string AProp { get; set; }
}
class MsgB : Msg
{
public int BProp { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment