繁体   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