0  缘由

  笔者最近在web api端使用Json.Net进行序列化处理,而在调用端使用DataContractSerializer进行反序列化,遇到日期时间处理反序列化不成功【备注:笔者使用Net Framework 4.0】。究其原因,Json.Net默认的日期输出是ISO标准时间,而微软默认的输出与解析日期格式是/Date(1242357713797+0800)/。可以看出我们只需将ISO的标准时间转换成微软能够识别日期时间格式即可。最后笔者就想重新对比下Net中Json序列化和反序列化的三种处理方式,以及性能。

1  介绍

Net中Json序列化反序列化一般常用的有三种:

  • JavaScriptSerializer[位于程序集:System.Web.Extension.dll,命令空间:System.Web.Script.Serialization]
  • DataContractSerializer[位于程序集:System.Runtime.Serialization.dll,命名空间:System.Runtime.Serialization.Json]
  • JsonConvert[位于程序集:Newtonsoft.Json.dll,命名空间:Newtonsoft.Json],外部引用库,可通过Nuget进行获取Json.Net

  笔者将分别对这三种进行序列化与反序列化复杂对象,使用Stopwatch进行监测其运行的时间。对比Stopwatch的运行时间,从而得出性能较佳的序列化Json的实现

2  三者对比

  新建一个Mvc3.0 项目命名为JsonConvertSample,使用Nuget引入Json.Net(在程序包管理器控制台键入:Install-Package Newtonsoft.Json),准备一个复杂类User,以及对比类JsonCompare。主要代码如下:

//=====================================================
//Copyright (C)   www.cnblogs.com/luge
//All rights reserved
//文件名:           JsonCompare
//创建时间:         2015-06-21
//当前登录用户名:   卤鸽
//描述:             
//======================================================
      
namespace JsonConvertSample.Models
{
    public class JsonCompare
    {
        public double DataContractSerializeTime { get; set; }

        public string DcsString { get; set; }

        public double JavascriptSerializeTime { get; set; }

        public string jsString { get; set; }

        public double JsonNetTime { get; set; }

        public string jnString { get; set; }

        public int Capacity { get; set; }
    }

}

namespace JsonConvertSample.Models
{
    public class User
    {

        public int UserID { get; set; }

        public string UserName { get; set; }

        public decimal Saraly { get; set; }

        public Address Location { get; set; }

        public List<School> Schools { get; set; }



        public DateTime BirthDate { get; set; }
    }

    public class Address
    {
        public string Province { get; set; }


        public string City { get; set; }
    }

    public class School
    {
        public string SchoolName { get; set; }

        public string SchoolDesc { get; set; }
    }
}
View Code

相关文章:

  • 2021-09-15
  • 2020-07-18
  • 2022-12-23
  • 2022-03-08
  • 2021-12-15
  • 2021-07-13
  • 2021-07-30
  • 2022-02-08
猜你喜欢
  • 2021-07-06
  • 2022-12-23
  • 2021-08-31
  • 2021-06-29
  • 2022-12-23
  • 2021-10-18
  • 2022-12-23
相关资源
相似解决方案