c# - Initializing object data in the constructor by deserializing a json file -


ok want rid of first constructor, , able deserialize directly. there way pull each variable json 1 @ time? or there blanket statement use pull them @ once , populate object.

 public masteremailsettings()  {       _user = "";       _password = "";       _domain = "";       _emailaddress = "";  }  public masteremailsettings(string path)  {       var tempobject = new masteremailsettings();        try       {            tempobject = jsonconvert.deserializeobject<masteremailsettings>(file.readalltext(path));            _domain = tempobject.domain;            _password = tempobject.password;            _user = tempobject.user;            _emailaddress = tempobject.emailaddress;       }       catch (exception ex)       {            console.writeline(ex.tostring());       }  } 

personally, wouldn't create constructor going responsible going out disk, reading in file, using 3rd party lib deserialize object, take bits of deserialized object , put fields on class. normally, constructor conveys object initialization, , instead wrapping lot of responsibility constructor i'm not sure need anyway.

one suggestion have if want encapsulate logic space on class create factory method. factory method indicates more broadly there actual work done in order initialize type:

public static masteremailsettings create(string path){     return jsonconvert.deserializeobject<masteremailsettings>(file.readalltext(path)) } 

i'm not entirely sure on use case original constructor code sets tempobject deserialized form of object set few fields it? we'd need little more information on that.

again, better off using...

var emailsettings = jsonconvert.deserializeobject<masteremailsettings>(file.readalltext(path))  

...in code wherever you're wanting feature, if you'd encapsulate bit, factory method above path go down.

* update * i've read in comment don't want place try/catch around whenever want load information disk , makes sense. factory method above + try catch logic catch ioexception explicitly impl.

public static masteremailsettings create(string path){     try{         return jsonconvert.deserializeobject<masteremailsettings>(file.readalltext(path))     }     catch(ioexception ex)     {         //answer how system should respond in event file did not exist. maybe want log , throw?         throw; //do not use throw ex re-start stack trace point exception thrown. use either throw or throw new someexception("", ex); make sure original stack trace on exception preserved.     } } 

there other exceptions readalltext can throw, may want consider them , how code should respond them: https://msdn.microsoft.com/en-us/library/ms143368(v=vs.110).aspx


Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -