zoukankan      html  css  js  c++  java
  • 重构Web Api程序(Api Controller和Entity)续篇

    昨天有写总结《重构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)方法:

    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)函数:

    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


    私有 List<T> IoDeserialize<T>(string filePath)函数:

     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

    这样在OrderEntity.cs类别中,我们就可以删除下面2个方法或是函数:



    在相对应的引用此私有方法的代码,需要修改为JsonUtility.cs的方法:

     
    下列内容于2015-03-23 11:00分补充与完善:
    重构Web Api程序(Api Controller和Entity) 续篇(1)http://www.cnblogs.com/insus/p/4359733.html

  • 相关阅读:
    第十四周学习进度总结
    第十三周学习进度总结
    第十二周学习进度总结
    第十一周学习进度总结
    第十周学习进度总结
    第九周学习进度总结
    第八周学习进度总结
    day16-机器学习十讲第一讲
    day15-验证码识别
    day14-卷积网络识别手写数字
  • 原文地址:https://www.cnblogs.com/insus/p/4355619.html
Copyright © 2011-2022 走看看