Advertisement
Guest User

question-15865756

a guest
Apr 7th, 2013
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.10 KB | None | 0 0
  1.     class Program
  2.     {
  3.         static void Main(string[] args)
  4.         {
  5.             string json = SerializeStuff();
  6.             Console.WriteLine(json);
  7.             MyClass obj = DeserializeStuff(json);
  8.             Console.WriteLine(obj.Action.ActionType);
  9.             Console.WriteLine((obj.Action as SettingsAction).SettingsType);
  10.         }
  11.  
  12.         static string SerializeStuff()
  13.         {
  14.             MyClass obj = new MyClass
  15.             {
  16.                 Action = new SettingsAction { SettingsType = SettingsType.Bar }
  17.             };
  18.  
  19.             string json = JsonConvert.SerializeObject(
  20.                             obj,
  21.                             Formatting.Indented,
  22.                             new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All });
  23.  
  24.             return json;
  25.         }
  26.  
  27.         static MyClass DeserializeStuff(string json)
  28.         {
  29.             return JsonConvert.DeserializeObject<MyClass>(json);
  30.         }
  31.     }
  32.  
  33.  
  34.     public abstract class ModelBase
  35.     {
  36.     }
  37.  
  38.     public class MyClass : ModelBase
  39.     {
  40.         public string Title { get; set; }
  41.  
  42.         [JsonProperty(TypeNameHandling = TypeNameHandling.All)]
  43.         public MyAction Action { get; set; }
  44.     }
  45.  
  46.     public abstract class MyAction : ModelBase
  47.     {
  48.         [JsonIgnore()]
  49.         public abstract ActionType ActionType { get; }
  50.         public abstract void Execute();
  51.     }
  52.  
  53.     public enum ActionType
  54.     {
  55.         None,
  56.         Settings
  57.     }
  58.  
  59.     public enum SettingsType
  60.     {
  61.         Foo,
  62.         Bar
  63.     }
  64.  
  65.     public class SettingsAction : MyAction
  66.     {
  67.         public override ActionType ActionType
  68.         {
  69.             get { return ActionType.Settings; }
  70.         }
  71.  
  72.         public SettingsType SettingsType { get; set; }
  73.  
  74.         public override void Execute()
  75.         {
  76.  
  77.         }
  78.     }
  79.  
  80.     public class NoneAction : MyAction
  81.     {
  82.         public override ActionType ActionType
  83.         {
  84.             get { return ActionType.None; }
  85.         }
  86.  
  87.         public override void Execute()
  88.         {
  89.             return;
  90.         }
  91.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement