Nancy使用轉換器擴展序列化

使用場景

以時間爲例,若要將時間的年月日指定爲3個輸入框的話,傳遞的參數可能是這樣的:

{"date":{"year":2019,"month":1,"day":31}}

擴展序列化DateTime

爲了更方便的進行數據轉換,我們可以擴展Nancy的JavaScriptConverter以攔截DateTime值的序列化和反序列化,我們可以自定義返回任何類型的數據:

using Nancy.Json;
using System;
using System.Collections.Generic;

namespace CoreNancy.Custom
{
    public class CustomDateTimePartsConverter : JavaScriptConverter
    {
        //向序列化系統指示轉換器將處理哪些數據類型
        public override IEnumerable<Type> SupportedTypes
        {
            //處理DateTime數據類型
            get { yield return typeof(DateTime); }
        }

        //反序列化
        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            if (type == typeof(DateTime))
            {
                object year, month, day;

                dictionary.TryGetValue("year", out year);
                dictionary.TryGetValue("month", out month);
                dictionary.TryGetValue("day", out day);

                try
                {
                    return new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), Convert.ToInt32(day));
                }
                catch 
                {
                    return null;
                }

            }

            return null;
        }

        //序列化
        public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
        {
            if (obj is DateTime)
            {
                DateTime date = (DateTime)obj;

                var json = new Dictionary<string, object>();

                json["year"] = date.Year;
                json["month"] = date.Month;
                json["day"] = date.Day;

                return json;
            }

            return null;
        }
    }
}

如何使用?

創建JavaScriptSerializer對象,調用JavaScriptSerializer對象的RegisterConverters方法顯式註冊轉換器。

using CoreNancy.Custom;
using Nancy;
using Nancy.Json;
using System;
using System.Collections.Generic;

namespace CoreNancy.Module
{
    public class SerializationModule : NancyModule
    {
        private JavaScriptSerializer serializer = new JavaScriptSerializer();
        private IEnumerable<JavaScriptConverter> converters
        {
            get { yield return new CustomDateTimePartsConverter(); }
        }
        public SerializationModule()
        {
            serializer.RegisterConverters(converters);
            Get("/Serialization/{date}", p =>
            {
                DateTime d = serializer.Deserialize<DateTime>(p.date);
                return d == null ? null : d.ToString();
            });
            Get("/Serialization/", p =>
            {
                return serializer.Serialize(DateTime.Now);
            });
        }
    }
}

效果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章