为了账号安全,请及时绑定邮箱和手机立即绑定

重构Web Api程序

标签:
JavaScript



有最后的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

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
移动开发工程师
手记
粉丝
18
获赞与收藏
134

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消