Rebuild the Web Api Program (Api Controller and Entity ).
Yesterday I wrote a summary titled restructuring Web Api programs (Api Controller and Entity.
Of the last four private methods, two of them are serialized, And the List <T> sequence is converted into a json file, the other is to convert the reverse sequence of the json file to a generic List <T>.
Considering that they can be referenced or used in future projects. Insus. NET restructured them into a brand new Utility class:
Void GenericListToJsonFile <T> (List <T> listT, string filePath) method:
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 );}}View Code
List <T> JsonFileToGenericList <T> (string filePath) function:
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 ;}View Code
Private List <T> IoDeserialize <T> (string filePath) function:
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 ;}}View Code
In this way, in the OrderEntity. cs category, we can delete the following two methods or functions:
In the corresponding code that references this private method, you need to modify it to the JsonUtility. cs method:
The following content was supplemented and improved at on May 23:
Refactoring Web Api Program (Api Controller and Entity) continued (1) http://www.cnblogs.com/insus/p/4359733.html