簡體   English   中英

JavaScriptSerializer不使用CultureInfo.CurrentCulture

[英]JavaScriptSerializer not using CultureInfo.CurrentCulture

如何從System.Web.Extensions獲取JavaScriptSerializer以使用CultureInfo.CurrentCulture?

我收到反序列化DD / MM / YYYY DateTimes的異常,因為它目前期望它們采用美國格式,這對於我們的應用程序是不正確的。

根據JavaScriptSerializer上的MDSN注釋:

Date對象,在JSON中表示為“ / Date(滴答數)/”。 刻度數是一個正或負的長值,它表示自UTC 1970年1月1日午夜以來經過的刻度數(毫秒)。

支持的最大日期值為MaxValue(12/31/9999 11:59:59 PM),最小的支持日期值為MinValue(1/1/0001 12:00:00 AM)。

您需要為DateTime注冊一個處理您的類型的JavaScriptConverter

public class DateTimeConverter : JavaScriptConverter
{

    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
        if (dictionary == null)
            throw new ArgumentNullException("dictionary");

        if (type == typeof(DateTime))
        {
            DateTime time;
            time = DateTime.Parse(dictionary["Time"].ToString(), /** put your culture info here **/);

            return time;
        }

        return null;
    }

    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
        DateTime? time = obj as DateTime?;

        if (time == null)
        {
            Dictionary<string, object> result = new Dictionary<string, object>();
            result["Time"] = time.Value;

            return result;
        }

        return new Dictionary<string, object>();
    }

    public override IEnumerable<Type> SupportedTypes
    {
        get { return new ReadOnlyCollection<Type>(new List<Type>(new Type[] { typeof(DateTime) })); }
    }
}

請記住,就對象屬性名稱而言,您需要考慮JSON的實際含義(您可能使用的不是“時間”名稱)。

在您的JavaScriptSerializer上注冊:

serializer.RegisterConverters(new List<JavaScriptConverter>() { new DateTimeConverter() });

最后,請注意還有很多事情可以做,這只是一個例子。 明確地,它正在搜索名稱為“ Time”的字典項,並且不處理解析失敗。 使用DateTime時,字段的名稱可能不止一個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM