使用DataContractJsonSerializer类将类型实例序列化为JSON字符串和反序列化为实例对象

前端之家收集整理的这篇文章主要介绍了使用DataContractJsonSerializer类将类型实例序列化为JSON字符串和反序列化为实例对象前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

一、JSON简介

JSON(JavaScript Object Notation,JavaScript对象表示法)是一种轻量级的数据交换格式。

JSON是“名值对”的集合。结构由大括号'{}',中括号'[]',逗号',',冒号':',双引号'“”'组成,包含的数据类型有Object,Number,Boolean,String,Array,NULL等。

JSON具有以下的形式:

对象(Object)是一个无序的“名值对”集合,一个对象以”{”开始,”}”结束。每个“名”后跟着一个”:”,多个“名值对”由逗号分隔。如:

{"FirstName":"Jason","LastName":"Chen"}

数组(Array)是值的有序集合,一个数组以“[”开始,“]”结束,值之间使用“,”分隔。如:

[{"FirstName":"Jason","LastName":"Chen"},{"FirstName":"Jason","LastName":"Chen"}]

字符串(String)是由双引号包围的任意数量Unicode字符的集合,使用反斜线转义。

二、对JSON数据进行序列化和反序列化

可以使用DataContractJsonSerializer类将类型实例序列化为JSON字符串,并将JSON字符串反序列化为类型实例。

利用DataContractJsonSerializer序列化和反序列化的代码

using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Text.RegularExpressions;
/*
 *  DataContractJsonSerializer在System.Runtime.Serialization.Json命名空间下,
 *  .NET Framework 3.5包含在System.ServiceModel.Web.dll中;
 *  .NET Framework 4.0包含在System.Runtime.Serialization中。
 *  create by cjj on 2014-10-08;email:ijasonchen91@sina.com<span style="font-family: Arial,Helvetica,sans-serif;">。</span>
 */
namespace mob.json
{

    /// <summary>
    /// JSON序列化和反序列化辅助类
    /// </summary>
    public class JsonHelper
    {
        /// <summary>
        /// JSON序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static string Serialize<T>(T t)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream();
            serializer.WriteObject(ms,t);
            string jsonString = Encoding.Default.GetString(ms.ToArray());
            ms.Close();
            jsonString = ConvertToDateTimeString(jsonString);
            return jsonString;
        }

        /// <summary>
        /// JSON反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonString"></param>
        /// <returns></returns>
        public static T Deserialize<T>(string jsonString)
        {

            jsonString = ConvertToJsonDateTimeString(jsonString);

            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString));
            T obj = (T)serializer.ReadObject(ms);
            ms.Close();
            return obj;
        }

        /// <summary>
        /// 将"\/Date(673286400000+0800)\/"Json时间格式替换"yyyy-MM-dd HH:mm:ss"格式的字符串
        /// </summary>
        /// <param name="jsonDateTimeString">"\/Date(673286400000+0800)\/"Json时间格式</param>
        /// <returns></returns>
        private static string ConvertToDateTimeString(string jsonDateTimeString)
        {
            string result = string.Empty;
            string p = @"\\/Date\((\d+)\+\d+\)\\/";
            MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
            Regex reg = new Regex(p);
            result = reg.Replace(jsonDateTimeString,matchEvaluator);
            return result;
        }

        private static string ConvertJsonDateToDateString(Match match)
        {
            string result = string.Empty;
            DateTime dt = new DateTime(1970,1,1);
            dt = dt.AddMilliseconds(long.Parse(match.Groups[1].Value));
            dt = dt.ToLocalTime();
            result = dt.ToString("yyyy-MM-dd HH:mm:ss");
            return result;
        }

        /// <summary>
        /// 将"yyyy-MM-dd HH:mm:ss"格式的字符串替换"\/Date(673286400000+0800)\/"Json时间格式
        /// </summary>
        /// <param name="dateTimeString">"yyyy-MM-dd HH:mm:ss"格式的字符串</param>
        /// <returns></returns>
        private static string ConvertToJsonDateTimeString(string dateTimeString)
        {
            string result = string.Empty;

            string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";
            MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate);
            Regex reg = new Regex(p);
            result = reg.Replace(dateTimeString,matchEvaluator);
            return result;
        }

        private static string ConvertDateStringToJsonDate(Match match)
        {
            string result = string.Empty;
            DateTime dt = DateTime.Parse(match.Groups[0].Value);
            dt = dt.ToUniversalTime();
            TimeSpan ts = dt - DateTime.Parse("1970-01-01");
            result = string.Format("\\/Date({0}+0800)\\/",ts.TotalMilliseconds);
            return result;
        }
    }
}

序列化Demo

简单对象Person

[DataContract]
public class Person
{
    public Person() { }

    public Person(string firstname,string lastname,DateTime birthday)
    {
        this.FirstName = firstname;
        this.LastName = lastname;
        this.Birthday = birthday;
    }

    [DataMember]
    public string FirstName { get; set; }
    [DataMember]
    public string LastName { get; set; }
    [DataMember]
    public DateTime Birthday { get; set; }
}

序列化为JSON字符串:

private void Serialize()
{
    Person p = new Person("Jason","Chen",Convert.ToDateTime("1991-05-04"));
    string jsonString = JsonHelper.Serialize<Person>(p);
    Response.Write(jsonString);
}

输出结果:

{"Birthday":"1991-05-04 00:00:00","FirstName":"Jason","LastName":"Chen"}

反序列化

private static void Deserialize()
{
    string jsonString = "{\"FirstName\":\"Jason\",\"LastName\":\"Chen\",\"Birthday\":\"1991-05-04 00:00:00\"}";
    Person p = JsonHelper.Deserialize<Person>(jsonString);
}
运行结果:

三、JSON序列化集合、字典、数组的处理

JSON数据中,所有的集合、字典和数组都表示为数组。

List<T> 序列化 :

private void Serialize()
{
    List<Person> list = new List<Person>(){
        new Person("Jason",Convert.ToDateTime("1991-05-04")),new Person("Jack",Convert.ToDateTime("1991-05-05"))
    };
    string jsonString = JsonHelper.Serialize<List<Person>>(list);
    Response.Write(jsonString);
}

序列化结果:

[{"Birthday":"1991-05-04 00:00:00",{"Birthday":"1991-05-05 00:00:00","FirstName":"Jack","LastName":"Chen"}]

Dictionary字典转化为JSON,如:

private void Serialize()
{
    Dictionary<string,string> dic = new Dictionary<string,string>();
    dic.Add("FirstName","Jason");
    dic.Add("LastName","Chen");
    string jsonString = JsonHelper.Serialize<Dictionary<string,string>>(dic);
    Response.Write(jsonString);
}

序列化结果:

[{"Key":"FirstName","Value":"Jason"},{"Key":"LastName","Value":"Chen"}]

猜你在找的Json相关文章