Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Program
- {
- static void Main(string[] args)
- {
- string json = SerializeStuff();
- Console.WriteLine(json);
- MyClass obj = DeserializeStuff(json);
- Console.WriteLine(obj.Action.ActionType);
- Console.WriteLine((obj.Action as SettingsAction).SettingsType);
- }
- static string SerializeStuff()
- {
- MyClass obj = new MyClass
- {
- Action = new SettingsAction { SettingsType = SettingsType.Bar }
- };
- string json = JsonConvert.SerializeObject(
- obj,
- Formatting.Indented,
- new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All });
- return json;
- }
- static MyClass DeserializeStuff(string json)
- {
- return JsonConvert.DeserializeObject<MyClass>(json);
- }
- }
- public abstract class ModelBase
- {
- }
- public class MyClass : ModelBase
- {
- public string Title { get; set; }
- [JsonProperty(TypeNameHandling = TypeNameHandling.All)]
- public MyAction Action { get; set; }
- }
- public abstract class MyAction : ModelBase
- {
- [JsonIgnore()]
- public abstract ActionType ActionType { get; }
- public abstract void Execute();
- }
- public enum ActionType
- {
- None,
- Settings
- }
- public enum SettingsType
- {
- Foo,
- Bar
- }
- public class SettingsAction : MyAction
- {
- public override ActionType ActionType
- {
- get { return ActionType.Settings; }
- }
- public SettingsType SettingsType { get; set; }
- public override void Execute()
- {
- }
- }
- public class NoneAction : MyAction
- {
- public override ActionType ActionType
- {
- get { return ActionType.None; }
- }
- public override void Execute()
- {
- return;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement