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

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

代码如下:

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

/// <summary>
    /// Person dummy class
    /// </summary>
    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<string> Friends
        {
            get;
            set;
        }
        public List<int> LoveNumbers
        {
            get;
            set;
        }
    }

代码如下:

接口定义  /// <summary>
    /// IJsonSerializer interface.
    /// </summary>
    interface IJsonSerializer
    {
        /// <summary>
        /// Serialize object to json string.
        /// </summary>
        /// <typeparam name="T">The type to be serialized.</typeparam>
        /// <param name="obj">Instance of the type T.</param>
        /// <returns>json string.</returns>
        string Serialize(object obj);

/// <summary>
        /// Deserialize json string to object.
        /// </summary>
        /// <typeparam name="T">The type to be deserialized.</typeparam>
        /// <param name="jsonString">json string.</param>
        /// <returns>instance of type T.</returns>
        T Deserialize<T>(string jsonString);
    }

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

代码如下:

/// <summary>
    /// Implement IJsonSerializer, but Deserialize had not been implemented.
    /// </summary>
    public class JsonSerializer : IJsonSerializer
    {
        /// <summary>
        /// Serialize object to json string.
        /// </summary>
        /// <typeparam name="T">The type to be serialized.</typeparam>
        /// <param name="obj">Instance of the type T.</param>
        /// <returns>json string.</returns>
        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();
        }

/// <summary>
        /// Deserialize json string to object.
        /// </summary>
        /// <typeparam name="T">The type to be deserialized.</typeparam>
        /// <param name="jsonString">json string.</param>
        /// <returns>instance of type T.</returns>
        public T Deserialize<T>(string jsonString)
        {
            throw new NotImplementedException("Not implemented :(");
        }

/// <summary>
        /// Get array json format string value.
        /// </summary>
        /// <param name="obj">array object</param>
        /// <returns>js format array string.</returns>
        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";
        }

/// <summary>
        /// Get Ilist json format string value.
        /// </summary>
        /// <param name="obj">IList object</param>
        /// <returns>js format IList string.</returns>
        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";
        }

/// <summary>
        /// Check whether t is array type.
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        bool isArrayType(Type t)
        {
            if (t != null)
            {
                return t.IsArray;
            }

return false;
        }

/// <summary>
        /// Check whether t is custom class type.
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        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<string>() { "friend1", "friend2" },
                LoveNumbers = new List<int>() { 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]}

(0)

相关推荐

  • JavaScript中的对象序列化介绍

    与Java语言一样,JavaScript中可以对对象进行序列化和反序列化,藉此对对象进行保存.ECMAScript 5标准中,JavaScript中的对象序列化是通过JSON.stringify()来实现的,而反序列化则通过JSON.parse()来实现: 复制代码 代码如下: var o = {x:1, y:29, z:42}; var s = JSON.stringify(o); console.log(s);//{"x":1,"y":29,"z&qu

  • js解析与序列化json数据(二)序列化探讨

    上一节我们讲解了JSON.stringify()的基本用法,这一节我们来重点探讨一下序列化. JSON.stringify()除了要序列化的js对象外,还可以接收另外两个参数,这两个参数用于指定不同方式序列化js对象.第一个参数是过滤器,可以使一个数组,也可以是一个函数:第二个参数是一个选项,表示是否在JSON字符串中保留缩进.单独或组合使用这两个参数,可以更全面深入地控制JSON的序列化. 1.过滤结果 如果过滤器参数是数组,那么JSON.stringify()的结果中将只包含数组中列出的属性

  • js解析与序列化json数据(一)json.stringify()的基本用法

    早期的JSON解析器基本上就是使用JavaScript的eval()函数.由于JSON是JavaScript语法的自己,因此eval()函数可以解析.解释并返回JavaScript的对象和数组. ECMAScript 5对解析JSON的行为进行了规范,定义了全局对象JSON. JSON对象有两个方法:stringify()和parse().在最简单的情况下,这两个方法分别用于把JavaScript对象序列化为JSON字符串和把JSON字符串解析为原生JavaScript.例如: 新建一个HTML

  • 详解JavaScript对象序列化

    一.什么是对象序列化? 对象序列化是指将对象的状态转换为字符串(来自我这菜鸟的理解,好像有些书上也是这么说的,浅显易懂!): 序列化(Serialization)是将对象的状态信息转换为可以存储或传输的形式的过程(来自"百度百科-序列化",学术性强,略显高端): 二.为什么会有对象序列化? 世间万物,都有其存在的原因.为什么会有对象序列化呢?因为程序猿们需要它.既然是对象序列化,那我们就先从一个对象说起: var obj = {x:1, y:2}; 当这句代码运行时,对象obj的内容会

  • Json序列化和反序列化方法解析

    复制代码 代码如下: /// <summary>        /// Json序列化,用于发送到客户端        /// </summary>        public static string ToJsJson(this object item)        { DataContractJsonSerializer serializer = new DataContractJsonSerializer(item.GetType()); using (MemoryStr

  • 浅析JSON序列化与反序列化

    方法一:引入System.Web.Script.Serialization命名空间使用 JavaScriptSerializer类实现简单的序列化序列化类:Personnel 复制代码 代码如下: public class Personnel        {            public int Id { get; set; }            public string Name { get; set; }        } 执行序列化反序列化: 复制代码 代码如下: prote

  • Jquery 组合form元素为json格式,asp.net反序列化

    作者:敖士伟 Email:ikmb@163.com 转载注明作者 说明: 1.js根据表单元素class属性,把表单元素的name和value组合为json格式;用表单元素class属性可以针对性地组合JSON数据. 2.后端ASP.NET用JavaScriptSerializer反序列化为对象实列. 3.好处:简化了前端数据读取与后端数据赋值. 复制代码 代码如下: function GetJSONStr(class_name) { var a = []; //文本框 $("." +

  • 使用 ServiceStack.Text 序列化 json的实现代码

    相信做 .net 开发的朋友经常会遇到 json 序列化这样的需要,今天发篇文章总结下自己使用ServiceStack.Text 来序列化 json.它的速度比 Newtonsoft.Json 快很多,在测试时发现比 fastJson 还快些. 首先,我们有下边两个类,一个是职员(Staff)类,一个是联系方式(Contact)类: 复制代码 代码如下: public class Staff{    public long ID { get; set; }    public string Na

  • C#实现json的序列化和反序列化实例代码

    在做asp.net和unity进行http通信的时候,当unity客户端发出表单请求的时候,我要将他要请求的数据以json的格式返回给客户端,让客户端来解析.服务器端这一块就涉及到json的序列化和反序列化的问题. 两种方法都有例子,第一种是用泛型集合来存储的对象,然后将集合序列化一下:第二种是直接序列化的一个对象 复制代码 代码如下: using System;using System.Collections.Generic;using System.Web.Script.Serializat

  • jquery序列化form表单使用ajax提交后处理返回的json数据

    1.返回json字符串: 复制代码 代码如下: /** 将一个字符串输出到浏览器 */     protected void writeJson(String json) {         PrintWriter pw = null;         try {             servletResponse.setContentType("text/plain;charset=UTF-8");             pw = servletResponse.getWrit

随机推荐