当前位置:  编程技术>.net/c#/asp.net

C#实现简单的JSON序列化功能代码实例

    来源: 互联网  发布时间:2014-10-24

    本文导语:   好久没有做web了,JSON目前比较流行,闲得没事,所以动手试试将对象序列化为JSON字符(尽管DotNet Framework已经有现成的库,也有比较好的第三方开源库),而且只是实现了处理简单的类型,并且DateTime处理的也不专业,有兴趣的...

 好久没有做web了,JSON目前比较流行,闲得没事,所以动手试试将对象序列化为JSON字符(尽管DotNet Framework已经有现成的库,也有比较好的第三方开源库),而且只是实现了处理简单的类型,并且DateTime处理的也不专业,有兴趣的筒子可以扩展,代码比较简单,反序列化木有实现:( ,直接贴代码吧,都有注释了,所以废话不多说  :)

代码如下:

测试类///
    /// Nested class of Person.
    ///
    public class House
    {
        public string Name
        {
            get;
            set;
        }
        public double Price
        {
            get;
            set;
        }
    }

    ///
    /// Person dummy class
    ///
    public class Person
    {
        public string Name
        {
            get;
            set;
        }
        public int Age
        {
            get;
            set;
        }
        public string Address
        {
            get;
            set;
        }
        private int h = 12;

        public bool IsMarried
        {
            get;
            set;
        }

        public string[] Names
        {
            get;
            set;
        }

        public int[] Ages
        {
            get;
            set;
        }
        public House MyHouse
        {
            get;
            set;
        }
        public DateTime BirthDay
        {
            get;
            set;
        }
        public List Friends
        {
            get;
            set;
        }
        public List LoveNumbers
        {
            get;
            set;
        }
    }

代码如下:

接口定义  ///
    /// IJsonSerializer interface.
    ///
    interface IJsonSerializer
    {
        ///
        /// Serialize object to json string.
        ///
        /// The type to be serialized.
        /// Instance of the type T.
        /// json string.
        string Serialize(object obj);

        ///
        /// Deserialize json string to object.
        ///
        /// The type to be deserialized.
        /// json string.
        /// instance of type T.
        T Deserialize(string jsonString);
    }

接口实现,还有待完善..

代码如下:

///
    /// Implement IJsonSerializer, but Deserialize had not been implemented.
    ///
    public class JsonSerializer : IJsonSerializer
    {
        ///
        /// Serialize object to json string.
        ///
        /// The type to be serialized.
        /// Instance of the type T.
        /// json string.
        public string Serialize(object obj)
        {
            if (obj == null)
            {
                return "{}";
            }

            // Get the type of obj.
            Type t = obj.GetType();

            // Just deal with the public instance properties. others ignored.
            BindingFlags bf = BindingFlags.Instance | BindingFlags.Public;

            PropertyInfo[] pis = t.GetProperties(bf);

            StringBuilder json = new StringBuilder("{");

            if (pis != null && pis.Length > 0)
            {
                int i = 0;
                int lastIndex = pis.Length - 1;

                foreach (PropertyInfo p in pis)
                {
                    // Simple string
                    if (p.PropertyType.Equals(typeof(string)))
                    {
                        json.AppendFormat(""{0}":"{1}"", p.Name, p.GetValue(obj, null));
                    }
                    // Number,boolean.
                    else if (p.PropertyType.Equals(typeof(int)) ||
                        p.PropertyType.Equals(typeof(bool)) ||
                        p.PropertyType.Equals(typeof(double)) ||
                        p.PropertyType.Equals(typeof(decimal))
                        )
                    {
                        json.AppendFormat(""{0}":{1}", p.Name, p.GetValue(obj, null).ToString().ToLower());
                    }
                    // Array.
                    else if (isArrayType(p.PropertyType))
                    {
                        // Array case.
                        object o = p.GetValue(obj, null);

                        if (o == null)
                        {
                            json.AppendFormat(""{0}":{1}", p.Name, "null");
                        }
                        else
                        {
                            json.AppendFormat(""{0}":{1}", p.Name, getArrayValue((Array)p.GetValue(obj, null)));
                        }
                    }
                    // Class type. custom class, list collections and so forth.
                    else if (isCustomClassType(p.PropertyType))
                    {
                        object v = p.GetValue(obj, null);
                        if (v is IList)
                        {
                            IList il = v as IList;
                            string subJsString = getIListValue(il);

                            json.AppendFormat(""{0}":{1}", p.Name, subJsString);
                        }
                        else
                        {
                            // Normal class type.
                            string subJsString = Serialize(p.GetValue(obj, null));

                            json.AppendFormat(""{0}":{1}", p.Name, subJsString);
                        }
                    }
                    // Datetime
                    else if (p.PropertyType.Equals(typeof(DateTime)))
                    {
                        DateTime dt = (DateTime)p.GetValue(obj, null);

                        if (dt == default(DateTime))
                        {
                            json.AppendFormat(""{0}":""", p.Name);
                        }
                        else
                        {
                            json.AppendFormat(""{0}":"{1}"", p.Name, ((DateTime)p.GetValue(obj, null)).ToString("yyyy-MM-dd HH:mm:ss"));
                        }
                    }
                    else
                    {
                        // TODO: extend.
                    }

                    if (i >= 0 && i != lastIndex)
                    {
                        json.Append(",");
                    }

                    ++i;
                }
            }

            json.Append("}");

            return json.ToString();
        }

        ///
        /// Deserialize json string to object.
        ///
        /// The type to be deserialized.
        /// json string.
        /// instance of type T.
        public T Deserialize(string jsonString)
        {
            throw new NotImplementedException("Not implemented :(");
        }

        ///
        /// Get array json format string value.
        ///
        /// array object
        /// js format array string.
        string getArrayValue(Array obj)
        {
            if (obj != null)
            {
                if (obj.Length == 0)
                {
                    return "[]";
                }

                object firstElement = obj.GetValue(0);
                Type et = firstElement.GetType();
                bool quotable = et == typeof(string);

                StringBuilder sb = new StringBuilder("[");
                int index = 0;
                int lastIndex = obj.Length - 1;

                if (quotable)
                {
                    foreach (var item in obj)
                    {
                        sb.AppendFormat(""{0}"", item.ToString());

                        if (index >= 0 && index != lastIndex)
                        {
                            sb.Append(",");
                        }

                        ++index;
                    }
                }
                else
                {
                    foreach (var item in obj)
                    {
                        sb.Append(item.ToString());

                        if (index >= 0 && index != lastIndex)
                        {
                            sb.Append(",");
                        }

                        ++index;
                    }
                }

                sb.Append("]");

                return sb.ToString();
            }

            return "null";
        }

        ///
        /// Get Ilist json format string value.
        ///
        /// IList object
        /// js format IList string.
        string getIListValue(IList obj)
        {
            if (obj != null)
            {
                if (obj.Count == 0)
                {
                    return "[]";
                }

                object firstElement = obj[0];
                Type et = firstElement.GetType();
                bool quotable = et == typeof(string);

                StringBuilder sb = new StringBuilder("[");
                int index = 0;
                int lastIndex = obj.Count - 1;

                if (quotable)
                {
                    foreach (var item in obj)
                    {
                        sb.AppendFormat(""{0}"", item.ToString());

                        if (index >= 0 && index != lastIndex)
                        {
                            sb.Append(",");
                        }

                        ++index;
                    }
                }
                else
                {
                    foreach (var item in obj)
                    {
                        sb.Append(item.ToString());

                        if (index >= 0 && index != lastIndex)
                        {
                            sb.Append(",");
                        }

                        ++index;
                    }
                }

                sb.Append("]");

                return sb.ToString();
            }

            return "null";
        }

        ///
        /// Check whether t is array type.
        ///
        ///
        ///
        bool isArrayType(Type t)
        {
            if (t != null)
            {
                return t.IsArray;
            }

            return false;
        }

        ///
        /// Check whether t is custom class type.
        ///
        ///
        ///
        bool isCustomClassType(Type t)
        {
            if (t != null)
            {
                return t.IsClass && t != typeof(string);
            }

            return false;
        }
    }

测试代码:

代码如下:

class Program
    {
        static void Main(string[] args)
        {
            Person ps = new Person()
            {
                Name = "Leon",
                Age = 25,
                Address = "China",
                IsMarried = false,
                Names = new string[] { "wgc", "leon", "giantfish" },
                Ages = new int[] { 1, 2, 3, 4 },
                MyHouse = new House()
                {
                    Name = "HouseName",
                    Price = 100.01,
                },
                BirthDay = new DateTime(1986, 12, 20, 12, 12, 10),
                Friends = new List() { "friend1", "friend2" },
                LoveNumbers = new List() { 1, 2, 3 }
            };

            IJsonSerializer js = new JsonSerializer();
            string s = js.Serialize(ps);
            Console.WriteLine(s);
            Console.ReadKey();
        }
    }

 生成的 JSON字符串 :

 

代码如下:

 {"Name":"Leon","Age":25,"Address":"China","IsMarried":false,"Names":["wgc","leon","giantfish"],"Ages":[1,2,3,4],"MyHouse":{"Name":"HouseName","Price":100.01},"BirthDay":"1986-12-20 12:12:10","Friends":["friend1","friend2"],"LoveNumbers":[1,2,3]}
 


    
 
 

您可能感兴趣的文章:

  • c#通过委托delegate与Dictionary实现action选择器代码举例
  • C#实现获取枚举中元素个数的方法
  • C#实现自定义双击事件
  • C#键盘输入回车键实现点击按钮效果的方法
  • C#实现获取一年中是第几个星期的方法
  • C#实现Datatable排序的方法
  • C#实现装箱与拆箱操作简单实例
  • 解决C#中WebBrowser的DocumentCompleted事件不执行的实现方法
  • C#下实现创建和删除目录的实例代码
  • 使用C#实现在屏幕上画图效果的代码实例
  • C#实现过滤html标签并保留a标签的方法
  • c#实现TextBox只允许输入数字
  • C# Winform 整个窗口拖动的实现代码
  • c# ListView实现双击Item事件的变通方法
  • C#实现随鼠标移动窗体实例
  • C#中的FileUpload 选择后的预览效果具体实现
  • C# 窗体隐藏及任务管理器中禁止关闭的实现代码
  • C#的锯齿数组以及C++实现代码
  • C#格式化文件大小的实现代码
  • C#怎样才能实现窗体最小化到托盘呢?
  • C# char类型字符转换大小写的实现代码
  • java序列化实现Serializable接口
  • .net实现序列化与反序列化实例解析
  • 怎样实现对象的序列化
  • C#实现json的序列化和反序列化实例代码
  • jQuery中验证表单提交方式及序列化表单内容的实现
  • C#实现复杂XML的序列化与反序列化
  • Android xml文件的序列化实现代码
  • 基于序列化存取实现java对象深度克隆的方法详解
  •  
    本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
    本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。












  • 相关文章推荐
  • C#获得MAC地址(网卡序列号)的实现代码
  • C语言实现最长递增子序列问题的解决方法
  • Android读取用户号码,手机串号,SIM卡序列号的实现代码
  • Oracle中使用触发器(trigger)和序列(sequence)模拟实现自增列实例
  • C#获取cpu序列号、硬盘ID、网卡MAC地址的实现代码
  • C++实现二叉树遍历序列的求解方法
  • java生成申请单序列号的实现方法
  • 通过javascript实现DIV居中,兼容各浏览器版本
  • socket实现多文件并发传输,求助多线程实现问题?
  • Python GUI编程:tkinter实现一个窗口并居中代码
  • interface 到底有什么用???实现接口,怎么实现??
  • 通过javascript库JQuery实现页面跳转功能代码
  • 怎么用Jsp实现在页面实现树型结构?
  • sharepoint 2010 使用STSNavigate函数实现文件下载举例
  • windows 下的PortTunnel 在linux下怎么实现?或者相应的已经实现的软件?端口映射
  • php实现socket实现客户端和服务端数据通信源代码
  • 网站重定向用C语言实现iptables,ACL实现
  • flash AS3反射实现(describeType和getDefinitionByName)
  • 在linux下如何编程实现nslookup命令实现的IP地址和域名互相转换的功能?
  • boost unordered_map和std::list相结合的实现LRU算法
  • 求在freebsd+Squid下实现pc上网的透明代理的实现方法!给出具体配置方法的高分谢!
  • 使用java jdk中的LinkedHashMap实现简单的LRU算法
  • linux下如实现与window下的驱动器实现文件共享??
  • iphone cocos2d 精灵的动画效果(图片,纹理,帧)CCAnimation实现
  • qt如何实现:操作键盘实现数据的滚动?
  • c语言判断某一年是否为闰年的各种实现程序代码
  • 我想用APPLET实现读取客户端的图片文件,该如何实现?
  • html<pre>标签自动换行实现方法
  • PING是用TCP,还是用UDP来实现的?或是采用其它协议实现的?


  • 站内导航:


    特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

    ©2012-2021,,E-mail:www_#163.com(请将#改为@)

    浙ICP备11055608号-3