码迷,mamicode.com
首页 > 其他好文 > 详细

SerializerHelper

时间:2014-11-29 01:21:59      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   io   ar   color   os   sp   

bubuko.com,布布扣
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.IO;
 6 using System.Xml.Serialization;
 7 using System.Web.Script.Serialization;
 8 
 9 namespace CiWong.Admin.Common.Extensions
10 {
11     /// <summary>
12     /// 序列化帮助类
13     /// </summary>
14     public class SerializerHelper
15     {
16         /// <summary>
17         /// xml序列化
18         /// </summary>
19         /// <typeparam name="T">对象类型</typeparam>
20         /// <param name="obj">要序列化的对象</param>
21         /// <param name="strPath">保存的路径</param>
22         public static void XmlSerializer<T>(T obj, string strPath) where T : class
23         {
24             FileStream fs = new FileStream(strPath, FileMode.Create);
25             XmlSerializer xs = new XmlSerializer(typeof(T));
26             xs.Serialize(fs, obj);
27             fs.Close();
28         }
29 
30         /// <summary>
31         /// xml反序列化
32         /// </summary>
33         /// <typeparam name="T">对象类型</typeparam>
34         /// <param name="strPath">序列化文件保存的路径</param>
35         /// <returns>反序列化后的对象</returns>
36         public static T XmlDeserialize<T>(string strPath) where T : class
37         {
38             FileStream fs = new FileStream(strPath, FileMode.Open, FileAccess.Read);
39             XmlSerializer xs = new XmlSerializer(typeof(T));
40             var obj = xs.Deserialize(fs);
41             fs.Close();
42             return obj as T;
43         }
44 
45         /// <summary>
46         /// JSON序列化
47         /// </summary>
48         /// <typeparam name="T"></typeparam>
49         /// <param name="entity"></param>
50         /// <returns></returns>
51         public static string JsonSerializer<T>(T entity)
52         {
53             var serializer = new JavaScriptSerializer();
54             return serializer.Serialize(entity);
55         }
56 
57         /// <summary>
58         /// JSON反序列化
59         /// </summary>
60         /// <typeparam name="T"></typeparam>
61         /// <param name="jsonString"></param>
62         /// <returns></returns>
63         public static T JsonDeserialize<T>(string jsonString)
64         {
65             var serializer = new JavaScriptSerializer();
66             return serializer.Deserialize<T>(jsonString);
67         }
68     }
69 }
View Code

 

SerializerHelper

标签:des   style   blog   http   io   ar   color   os   sp   

原文地址:http://www.cnblogs.com/ccmo/p/4129659.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!