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


    class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("============================序列化单个对象为JSON格式======================================================");
                var jsonObj = GetUser().ToJsonString(); 
                Console.WriteLine(jsonObj + "
    
     ");
              
                Console.WriteLine("============================序列化集合对象为JSON格式======================================================");
                var jsonListObj = GetList().ToJsonString();
                Console.WriteLine(jsonListObj + "
    
     ");
             
                Console.WriteLine("============================序列化字符串集合======================================================");
                var jsonStrObj = GetString().ToJsonString();
                Console.WriteLine(jsonStrObj + "
    
     ");
    
                Console.WriteLine("============================构建一个JSON对象,反序列化为User对象===================================");
                //构建JSON对象
                string str = "{"Description":"少林袈裟旗舰店店长","Id":"1","Name":"少林扫地神僧"}";
                var user = str.ToJsonObject<User>();
                var entityObj = string.Format("json format str convert to user object:Id={0},Name={1},Description={2}", user.Id, user.Name, user.Description);
                Console.WriteLine(entityObj);
                Console.ReadKey();
            }
    
            public static User GetUser()
            {
                User user = new User()
                {
                    Id = 1,
                    Name = "无崖子",
                    Description = "逍遥派掌门"
                };
                return user;
            }
    
            public static List<User> GetList()
            {
                List<User> list = new List<User>() { 
                    new User(){ Id=1,Name="丁春秋", Description="星宿派掌门"},
                    new User(){ Id=2,Name="庄聚贤", Description="无所事事的帅哥"},
                    new User(){ Id=3,Name="段正淳", Description="风流倜傥大理王爷"}};
                return list;
            }
    
    
            public static IList<string> GetString()
            {
                IList<string> strList = new List<string>();
                strList.Add("乔峰");
                strList.Add("段誉");
                strList.Add("虚竹");
                return strList;
            }
        }
    
    
        public class User
        {
            public int Id { get; set; }
    
            public string Name { get; set; }
    
            public string Description { get; set; }
        }
    
    
    
        public static class StringExtensions
        {
            /// <summary>
            /// 将对象转化为Json字符串
            /// </summary>
            /// <typeparam name="T">对象类型</typeparam>
            /// <param name="instanse">对象本身</param>
            /// <returns>JSON字符串</returns>
            public static string ToJsonString<T>(this T instanse)
            {
                try
                {
                    DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(T));
                    using (MemoryStream ms = new MemoryStream())
                    {
                        js.WriteObject(ms, instanse);
                        ms.Flush();
                        ms.Seek(0, SeekOrigin.Begin);
                        StreamReader sr = new StreamReader(ms);
                        return sr.ReadToEnd();
                    }
                }
                catch
                {
                    return String.Empty;
                }
            }
    
            /// <summary>
            /// 将字符串转化为JSON对象,如果转换失败,返回default(T)
            /// </summary>
            /// <typeparam name="T">对象类型</typeparam>
            /// <param name="s">字符串</param>
            /// <returns>转换值</returns>
            public static T ToJsonObject<T>(this string s)
            {
                try
                {
                    DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(T));
                    using (MemoryStream ms = new MemoryStream())
                    {
                        StreamWriter sw = new StreamWriter(ms);
                        sw.Write(s);
                        sw.Flush();
                        ms.Seek(0, SeekOrigin.Begin);
                        return (T)js.ReadObject(ms);
                    }
                }
                catch
                {
                    return default(T);
                }
            }
        }

  • 相关阅读:
    vue 跨域访问http
    vue 生命周期小结
    koa的教程
    spoj104 HIGH
    loj2026 「JLOI / SHOI2016」成绩比较
    loj2024「JLOI / SHOI2016」侦查守卫
    loj2016 「SCOI2016」美味
    loj2014 「SCOI2016」萌萌哒
    loj2013 「SCOI2016」幸运数字
    loj2012 「SCOI2016」背单词
  • 原文地址:https://www.cnblogs.com/chenhaibo/p/3223048.html
Copyright © 2020-2023  润新知