c# - Deserializing inherited classes -


i want send parameter-settings backendapplication frontend. need able have different type of parameters (portnumbers, folders, static strings , such).

so i've designed baseclass, parameter such:

public abstract class parameter {     public abstract bool isvalid(); } 

let's have 2 types of folder parameters:

public abstract class folder : parameter {     public string foldername { get; set; }      protected folder(string foldername)     {         this.foldername = foldername;     } }  public class readwritefolder : folder {     public readwritefolder(string foldername) : base(foldername)     {     }      public override bool isvalid()     {         return isreadable() && iswritable();     } }  public class readfolder : folder {     public readfolder(string foldername) : base(foldername)     {     }      public override bool isvalid()     {         return isreadable();     } } 

this used webapi, controller:

public dictionary<string, parameter> get() {      dictionary<string, parameter> dictionary  = new dictionary<string, parameter>();     dictionary.add("temporaryfiles", new readwritefolder("c:\\temp\\"));     dictionary.add("anothertemporaryfiles", new readwritefolder("d:\\temp\\"));      return dictionary; } 

this yields following json-serialisation: {"temporaryfiles":{"foldername":"c:\\temp\\"},"anothertemporaryfiles":{"foldername":"d:\\temp\\"}} seems reasonable.

my question this: how can deserialize original types? or change serialization more easy deserialize?

what using serialization? if it's json.net (which many here suggest!), there's number of realted questions:

how deserialize json ienumerable newtonsoft json.net

but crux type name handling, decorate elements type information able deserialize them:

 jsonserializersettings settings = new jsonserializersettings  {     typenamehandling = typenamehandling.all  };  string strjson = jsonconvert.serializeobject(dictionary, settings); 

and should able deserialize directly.

var returndictionary = jsonconvert.deserializeobject<dictionary<string, parameter>>(strjson, settings) 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -