C # saving generic classes with json for Object Instantiation can easily save program settings,
It is used for permanent objects. Any program can be used and it depends on NewtonSoft. Used for json serialization and deserialization.
1 using Newtonsoft. json; 2 using System; 3 using System. collections. generic; 4 using System. IO; 5 using System. linq; 6 using System. text; 7 using System. threading. tasks; 8 9 namespace ConfigHandler10 {11 public class ConfigHandler <T> 12 where T: class13 {14 const string SAVE_PATH = "jsonconfig /"; 15 /// <summary> 16 // Singleton mode 17 /// </summary> 18 static T config; 19 private ConfigHandler () 20 {21 22} 23/ // <Summary> 24 // get the Save address, the default type is generic parameter T. The type name is 25 /// </summary> 26 /// <returns> </returns> 27 private static string GetSavePath () 28 {29 if (! Directory. exists (SAVE_PATH) 30 {31 Directory. createDirectory (SAVE_PATH); 32} 33 return $ "{SAVE_PATH} {typeof (T ). toString ()}. json "; 34} 35 // <summary> 36 // Save configuration 37 // </summary> 38 public static void Save (T _ config) 39 {40 config = _ config; 41 string json = JsonConvert. serializeObject (_ config); 42 try43 {44 using (var sw = new StreamWriter (GetSavePath () 45 {46 sw. writeAsync (json); 47} 48 49} 50 catch (E Xception) 51 {52 throw; 53} 54} 55 // <summary> 56 // obtain configuration information 57 // </summary> 58 // <returns> </returns> 59 public static T Load () 60 {61 if (config = null) 62 {63 string json = ""; 64 try65 {66 using (var sr = new StreamReader (GetSavePath ())) 67 {68 json = sr. readToEnd (); 69 if (json! = "") 70 {71 config = JsonConvert. deserializeObject <T> (json); 72} 73 else74 {75 config = null; 76} 77} 78} 79 catch (Exception) 80 {81 config = null; 82} 83} 84 return config; 85} 86 87} 88 89 90}
View Code
Demo:
using ConfigHandler;using ConsoleApplication1;using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication1{ class Program { static void Main(string[] args) { MyConfig config = new MyConfig(); config = new MyConfig(); config.name = "leiming"; config.Age = 20; config.Time = DateTime.Now; ConfigHandler<MyConfig>.Save(config); config = ConfigHandler<MyConfig>.Load(); Console.WriteLine(config.ToString()); Console.ReadKey(); } } class MyConfig { public int Hello{get;set;} public string name { get; set; } public int Age { get; set; } public DateTime Time { get; set; } public override string ToString() { return $"Name={name},Age={Age},Time={Time.ToShortDateString()}"; } }}
View Code