• C# Json 和对象的相互转换


    Json 和对象的相互转换

        /// <summary>
        /// Json 和对象的相互转换  ——需引用using Newtonsoft.Json;   即:Jsonnet.net.....
        /// </summary>
        public static class JsonHelper
        {
            /// <summary>
            /// 把对象转换为JSON字符串
            /// </summary>
            /// <param name="o">对象</param>
            /// <returns>JSON字符串</returns>
            public static string ObjectToJson(this object o)
            {
                if (o == null) return null;
                return JsonConvert.SerializeObject(o);
            }
    
            /// <summary>
            /// 把Json文本转为实体
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="input"></param>
            /// <returns></returns>
            public static T JsonToObject<T>(this string input)
            {
                try
                {
                    return JsonConvert.DeserializeObject<T>(input);
                }
                catch (Exception ex)
                {
                    return default(T);
                }
            }
      
        }
    

    使用如下所示:

      private void btnObjToJson_Click(object sender, EventArgs e)
            {
                List<Test> timePart = new List<Test>();
                timePart.Add(new Test { BeginTime = 8.10, EndTime = 8.15 });
                timePart.Add(new Test { BeginTime = 8.15, EndTime = 8.25 });
                timePart.Add(new Test { BeginTime = 8.26, EndTime = 8.55 });
    
                string json = JsonHelper.ObjectToJson(timePart);
                MessageBox.Show("json
    ==" + json);
            }
    
            private void btnJsonToObj_Click(object sender, EventArgs e)
            {
                List<Test> timePart = new List<Test>();
                timePart.Add(new Test { BeginTime = 8.10, EndTime = 8.15 });
                timePart.Add(new Test { BeginTime = 8.15, EndTime = 8.25 });
                timePart.Add(new Test { BeginTime = 8.26, EndTime = 8.55 });
    
                string json = JsonHelper.ObjectToJson(timePart);
    
                List<Test> list = JsonHelper.JsonToObject<List<Test>>(json);
                MessageBox.Show("list==" +list.Count);
            }
    

      

  • 相关阅读:
    android源码在线查看
    关于codereview工具与建议
    <转>如何进行code review
    [转] Android实时抓包分析 : 善用adb调试桥
    Swift:UIKit中Demo(一)
    Objective-C学习笔记(十)——循环语句for和do-while的使用
    一些牛人的IOS博客,mark下慢慢学习
    Visual Studio 2015速递(2)——提升效率和质量(VS2015核心竞争力)
    Web前端之基础知识
    通过金矿模型介绍动态规划
  • 原文地址:https://www.cnblogs.com/YYkun/p/10718746.html
Copyright © 2020-2023  润新知