昨天有寫總結《重構Web Api程序(Api Controller和Entity)》http://www.cnblogs.com/insus/p/4350111.html,把一些數據交換的移至OrderEntity類中去,並重構冗餘代碼。
有最後的4個私有方法中,其中有2個方法是實現序列化的,把List<T>序例後轉存爲json文件,另外一個是把json文件反序列轉換爲泛型List<T>。
考慮到未來在專案中,還能夠有能夠引用或使用到它們。Insus.NET把它們再重構到一個全新的Utility類中:
void GenericListToJsonFile<T>(List<T> listT, string filePath)方法:html
public static void GenericListToJsonFile<T>(List<T> listT, string filePath) { using (FileStream fs = File.Open(filePath, FileMode.CreateNew)) using (StreamWriter sw = new StreamWriter(fs)) using (JsonWriter jw = new JsonTextWriter(sw)) { jw.Formatting = Formatting.Indented; JsonSerializer serializer = new JsonSerializer(); serializer.Serialize(jw, listT); } }
List<T> JsonFileToGenericList<T>(string filePath)函數:json
public static List<T> JsonFileToGenericList<T>(string filePath) { List<T> listT = new List<T>(); if (File.Exists(filePath)) listT = IoDeserialize<T>(filePath); else { string physicalPath = HttpContext.Current.Server.MapPath(filePath); if (File.Exists(physicalPath)) listT = IoDeserialize<T>(physicalPath); } return listT; }
私有 List<T> IoDeserialize<T>(string filePath)函數:ide
private static List<T> IoDeserialize<T>(string filePath) { using (StreamReader sr = new StreamReader(filePath)) { JsonTextReader jtr = new JsonTextReader(sr); JsonSerializer se = new JsonSerializer(); object obj = se.Deserialize(jtr, typeof(List<T>)); return (List<T>)obj; } }
這樣在OrderEntity.cs類別中,咱們就能夠刪除下面2個方法或是函數:
在相對應的引用此私有方法的代碼,須要修改成JsonUtility.cs的方法:函數
下列內容於2015-03-23 11:00分補充與完善:
《重構Web Api程序(Api Controller和Entity) 續篇(1)》http://www.cnblogs.com/insus/p/4359733.htmlpost