JavaScriptSerializer不使用CultureInfo.CurrentCulture

时间:2011-10-24 17:37:08

标签: c# asp.net .net asp.net-mvc serialization

如何从System.Web.Extensions获取JavaScriptSerializer以使用CultureInfo.CurrentCulture?

我正在异常反序列化DD / MM / YYYY DateTimes,因为它目前期望它们采用美国格式,这对我们的应用程序来说是不正确的。

1 个答案:

答案 0 :(得分:1)

根据关于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)。

您需要为处理您的类型的JavaScriptConverter注册DateTime

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的字段,您可能只有一个名称。