.NET JSON对象序列化和反序列化

昨晚和几个哥们打字牌,打了个通宵,早上睡了2个多小时,发现精神还很抖擞(要是写代码有这么给力...哎。碉堡了)。闲来无事,打开VS,coding总结了下.NET序列化:

序列化定义:序列化是将对象状态转换为可保持或传输的格式的过程。与序列化相对的是反序列化,它将流转换为对象。这两个过程结合起来,可以轻松地存储和传输数据。

下面要介绍的是.net提供的序列化对象DataContractJsonSerializer,他主要是用于将对象转化为JSON格式数据以及将JSON反序列化为对象

直接上代码吧,可以直接在控制台打印出结果:

  1  class Program
  2     {
  3         static void Main(string[] args)
  4         {
  5             Console.WriteLine("============================序列化单个对象为JSON格式======================================================");
  6             var jsonObj = GetUser().ToJsonString(); 
  7             Console.WriteLine(jsonObj + "\n\r ");
  8           
  9             Console.WriteLine("============================序列化集合对象为JSON格式======================================================");
 10             var jsonListObj = GetList().ToJsonString();
 11             Console.WriteLine(jsonListObj + "\n\r ");
 12          
 13             Console.WriteLine("============================序列化字符串集合======================================================");
 14             var jsonStrObj = GetString().ToJsonString();
 15             Console.WriteLine(jsonStrObj + "\n\r ");
 16 
 17             Console.WriteLine("============================构建一个JSON对象,反序列化为User对象===================================");
 18             //构建JSON对象
 19             string str = "{\"Description\":\"少林袈裟旗舰店店长\",\"Id\":\"1\",\"Name\":\"少林扫地神僧\"}";
 20             var user = str.ToJsonObject<User>();
 21             var entityObj = string.Format("json format str convert to user object:Id={0},Name={1},Description={2}", user.Id, user.Name, user.Description);
 22             Console.WriteLine(entityObj);
 23             Console.ReadKey();
 24         }
 25 
 26         public static User GetUser()
 27         {
 28             User user = new User()
 29             {
 30                 Id = 1,
 31                 Name = "无崖子",
 32                 Description = "逍遥派掌门"
 33             };
 34             return user;
 35         }
 36 
 37         public static List<User> GetList()
 38         {
 39             List<User> list = new List<User>() { 
 40                 new User(){ Id=1,Name="丁春秋", Description="星宿派掌门"},
 41                 new User(){ Id=2,Name="庄聚贤", Description="无所事事的帅哥"},
 42                 new User(){ Id=3,Name="段正淳", Description="风流倜傥大理王爷"}};
 43             return list;
 44         }
 45 
 46 
 47         public static IList<string> GetString()
 48         {
 49             IList<string> strList = new List<string>();
 50             strList.Add("乔峰");
 51             strList.Add("段誉");
 52             strList.Add("虚竹");
 53             return strList;
 54         }
 55     }
 56 
 57 
 58     public class User
 59     {
 60         public int Id { get; set; }
 61 
 62         public string Name { get; set; }
 63 
 64         public string Description { get; set; }
 65     }
 66 
 67 
 68 
 69     public static class StringExtensions
 70     {
 71         /// <summary>
 72         /// 将对象转化为Json字符串
 73         /// </summary>
 74         /// <typeparam name="T">对象类型</typeparam>
 75         /// <param name="instanse">对象本身</param>
 76         /// <returns>JSON字符串</returns>
 77         public static string ToJsonString<T>(this T instanse)
 78         {
 79             try
 80             {
 81                 DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(T));
 82                 using (MemoryStream ms = new MemoryStream())
 83                 {
 84                     js.WriteObject(ms, instanse);
 85                     ms.Flush();
 86                     ms.Seek(0, SeekOrigin.Begin);
 87                     StreamReader sr = new StreamReader(ms);
 88                     return sr.ReadToEnd();
 89                 }
 90             }
 91             catch
 92             {
 93                 return String.Empty;
 94             }
 95         }
 96 
 97         /// <summary>
 98         /// 将字符串转化为JSON对象,如果转换失败,返回default(T)
 99         /// </summary>
100         /// <typeparam name="T">对象类型</typeparam>
101         /// <param name="s">字符串</param>
102         /// <returns>转换值</returns>
103         public static T ToJsonObject<T>(this string s)
104         {
105             try
106             {
107                 DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(T));
108                 using (MemoryStream ms = new MemoryStream())
109                 {
110                     StreamWriter sw = new StreamWriter(ms);
111                     sw.Write(s);
112                     sw.Flush();
113                     ms.Seek(0, SeekOrigin.Begin);
114                     return (T)js.ReadObject(ms);
115                 }
116             }
117             catch
118             {
119                 return default(T);
120             }
121         }
122     }

运行结果:

 

posted @ 2013-07-28 12:04  逐鹿天下  阅读(3564)  评论(14编辑  收藏  举报