DateTime的自定义JavaScriptConverter?

时间:2009-08-27 15:10:10

标签: .net javascript ajax converter

我有一个对象,它有一个DateTime属性...我想通过AJAX / JSON将该对象从.ashx处理程序传递回网页...我不想使用第三方控件.. 。

当我这样做时:

  new JavaScriptSerializer().Serialize(DateTime.Now);

我明白了:

  "\/Date(1251385232334)\/"

但是我想要“8/26/2009”(没关系本地化......我的应用程序是非常本地化的,所以我的日期格式化假设在这个问题中没有讨论)。如果我制作/注册自定义转换器

public class DateTimeConverter : JavaScriptConverter
{
    public override IEnumerable<Type> SupportedTypes
    {
        get { return new List<Type>() { typeof(DateTime), typeof(DateTime?) }; }
    }

    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
        Dictionary<string, object> result = new Dictionary<string, object>();
        if (obj == null) return result;
        result["DateTime"] = ((DateTime)obj).ToShortDateString();
        return result;
    }

    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
        if (dictionary.ContainsKey("DateTime"))
            return new DateTime(long.Parse(dictionary["DateTime"].ToString()), DateTimeKind.Unspecified);
        return null;
    }
}

然后我得到这个结果(因为自定义序列化方法的返回值是字典):

{"DateTime":"8/27/2009"}

所以现在在我的Javascript中,而不是做

somePerson.Birthday

我必须做

somePerson.Birthday.DateTime 

  or

somePerson.Birthday["DateTime"]

如何让自定义转换器返回一个直接字符串,以便我可以使用干净的Javascript?

10 个答案:

答案 0 :(得分:21)

JavaScriptSerializer绝对可以满足您的需求。

通过创建自定义转换器并将其注册到序列化程序,可以自定义JavaScriptSerializer为任何类型执行的序列化。如果你有一个名为Person的类,我们可以像这样创建一个转换器:

public class Person
{
    public string Name { get; set; }
    public DateTime Birthday { get; set; }
}

public class PersonConverter : JavaScriptConverter
{
    private const string _dateFormat = "MM/dd/yyyy";

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

    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
        Person p = new Person();
        foreach (string key in dictionary.Keys)
        {
            switch (key)
            {
                case "Name":
                    p.Name = (string)dictionary[key];
                    break;

                case "Birthday":
                    p.Birthday = DateTime.ParseExact(dictionary[key] as string, _dateFormat, DateTimeFormatInfo.InvariantInfo);
                    break;
            }
        }
        return p;
    }

    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
        Person p = (Person)obj;
        IDictionary<string, object> serialized = new Dictionary<string, object>();
        serialized["Name"] = p.Name;
        serialized["Birthday"] = p.Birthday.ToString(_dateFormat);
        return serialized;
    }
}

并像这样使用它:

JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new PersonConverter() });

Person p = new Person
            {
                Name = "User Name",
                Birthday = DateTime.Now
            };

string json = serializer.Serialize(p);
Console.WriteLine(json);
// {"Name":"User Name","Birthday":"12/20/2010"}

Person fromJson = serializer.Deserialize<Person>(json);
Console.WriteLine(String.Format("{0}, {1}", fromJson.Name, fromJson.Birthday)); 
// User Name, 12/20/2010 12:00:00 AM

答案 1 :(得分:11)

以下是对已接受答案的增强。

使用泛型,传递类型并使用反射来确定日期时间属性。

public class ExtendedJavaScriptConverter<T> : JavaScriptConverter where T : new()
{
    private const string _dateFormat = "dd/MM/yyyy";

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

    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
        T p = new T();

        var props = typeof(T).GetProperties();

        foreach (string key in dictionary.Keys)
        {
            var prop = props.Where(t => t.Name == key).FirstOrDefault();
            if (prop != null)
            {
                if (prop.PropertyType == typeof(DateTime))
                {
                    prop.SetValue(p, DateTime.ParseExact(dictionary[key] as string, _dateFormat, DateTimeFormatInfo.InvariantInfo), null);

                }
                else
                {
                    prop.SetValue(p, dictionary[key], null);
                }
            }
        }                  

        return p;
    }      

    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
        T p = (T)obj;
        IDictionary<string, object> serialized = new Dictionary<string, object>();

        foreach (PropertyInfo pi in typeof(T).GetProperties())
        {
            if (pi.PropertyType == typeof(DateTime))
            {
                serialized[pi.Name] = ((DateTime)pi.GetValue(p, null)).ToString(_dateFormat);
            }
            else
            {
                serialized[pi.Name] = pi.GetValue(p, null);
            }

        }

        return serialized;
    }

    public static JavaScriptSerializer GetSerializer() 
    {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        serializer.RegisterConverters(new[] { new ExtendedJavaScriptConverter<T>() });

        return serializer;
    }
}

用法很简单:

 JavaScriptSerializer serialiser = ExtendedJavaScriptConverter<Task>.GetSerializer();

希望能有所帮助。

答案 2 :(得分:9)

在不知道包装器类型甚至需要包装器对象的情况下,实际上有一种很好的干净方法。

您使用JavaScriptConverter将对象转换为也实现IDictionary的Uri。 JavaScriptSerializer会将其序列化为字符串。

这个黑客在这里描述:

http://blog.calyptus.eu/seb/2011/12/custom-datetime-json-serialization/

答案 3 :(得分:4)

实际上有一种丑陋的方式,为容器(Person / Article / Whatever)类创建一个JavaScriptConverter

容器:

public class Article
{
    public int Id { get; set; }
    public string Title { get; set; }
    public DateTime Date { get; set; }
}

转换器:

public class ArticleJavaScriptConverter : JavaScriptConverter
{
    public override IEnumerable<Type> SupportedTypes
    {
        get { return new Type[] { typeof(Article) }; }
    }

    public override object Deserialize(
        IDictionary<string, object> dictionary, 
        Type type, JavaScriptSerializer serializer)
    {
        DateTime date = 
            DateTime.ParseExact(dictionary["date"] as string, "s", null);

        return
            new Article()
            {
                Id = (int)dictionary["id"],
                Title = dictionary["title"] as string,
                Date = date
            };
    }

    public override IDictionary<string, object> Serialize(
        object obj, JavaScriptSerializer serializer)
    {
        var article = obj as Article;
        var result = new Dictionary<string,object>();

        if (article != null)
        {
            this.SerializeInternal(article, result);
        }

        return result;
    }

    private void SerializeInternal(
        Article article, IDictionary<string, object> result)
    {
        result.Add("id", article.Id);
        result.Add("title", article.Title);
        result.Add("date", article.Date.ToString("s"));
    }
}

永远幸福......

var serializer = new JavaScriptSerializer();

serializer.RegisterConverters(
    new JavaScriptConverter[] {
        new ArticleJavaScriptConverter() 
    });

var expected = new Article()
{
    Id = 3,
    Title = "test",
    Date = DateTime.Now
};


// {"id":3,"title":"test","date":"2009-12-02T05:12:00"}
var json = serializer.Serialize(article);

var actual = serializer.Deserialize<Article>(json);

Assert.AreEqual(expected, actual);

答案 4 :(得分:3)

我意识到答案有点晚了,但我最近找到了一个非常好的解决方案来解决这个问题。它在此博客文章中有记录,以防万一其他人认为它有用:http://icanmakethiswork.blogspot.co.uk/2012/04/beg-steal-or-borrow-decent-javascript.html

答案 5 :(得分:2)

答案是:你不能以这种方式使用JavaScriptConverter ......它没有这些功能。

但供参考:

How do I format a Microsoft JSON date? http://blog.stevenlevithan.com/archives/date-time-format

如果你关心,我最终做的是在javascript字符串原型中添加一个方法,以便在代码中使我更容易:

String.prototype.dateFromJSON = function () {
    return eval(this.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"));
};

在代码中使用这仍然很痛苦,因为你必须经常在所有地方调用dateFromJSON()...这是愚蠢的。

答案 6 :(得分:0)

我知道这看起来很愚蠢,但到目前为止我还没有找到更好的东西......我仍然在寻找,所以欢迎提出意见。

new JavaScriptSerializer().Serialize(DateTime.Now).Replace("\"\\/", "").Replace("\\/\"", "");

这只删除引号和斜杠,因此输出只是Date(123456789),虽然在技术上不是文字,但浏览器将其理解为实际日期值而不是字符串。

在JSON中,它看起来像这样

{"myDate":Date(123456789)}

我认为是黑客攻击。如果这实际上是在生产代码中实现的,我会亲自将其包装起来,或者像FormatForDates()这样的扩展方法,或者将序列化器本身包装成装饰器模式......或者在这种情况下,“undecorator”。我必须真的错过了这艘船,为什么这看起来很难。人们,我只是想约会! :-P

答案 7 :(得分:0)

@sambomartin对答案的vb.net转换。所有这一切归功于他。我只是粘贴这个以防万一有人需要这个为vb.net。

我还使其递归并添加了使用XmlElement数据注释覆盖默认属性名称的功能。 (XmlElementAttribute

Imports System.Web.Script.Serialization
Imports System.Linq
Imports System.Globalization
Imports System.Xml.Serialization

Public Class ExtendedJavaScriptSerializer(Of T As New)
    Inherits JavaScriptConverter

    Private Const _dateFormat As String = "dd/MM/yyyy"



    Public Overrides Function Deserialize(dictionary As IDictionary(Of String, Object), type As Type, serializer As JavaScriptSerializer) As Object
        Dim p As New T()
        Dim props = GetType(T).GetProperties()

        For Each key As String In dictionary.Keys
            Dim prop = props.Where(Function(x) x.Name = key).FirstOrDefault()
            If prop IsNot Nothing Then
                If prop.PropertyType = GetType(DateTime) Then
                    prop.SetValue(p, DateTime.ParseExact(CStr(dictionary(key)), _dateFormat, DateTimeFormatInfo.InvariantInfo), Nothing)
                Else
                    prop.SetValue(p, dictionary(key), Nothing)
                End If
            End If
        Next

        Return p

    End Function

    Public Overrides Function Serialize(obj As Object, serializer As JavaScriptSerializer) As IDictionary(Of String, Object)
        Dim serialized As IDictionary(Of String, Object) = New Dictionary(Of String, Object)
        CheckProperties(obj, serialized)
        Return serialized
    End Function

    Public Overrides ReadOnly Property SupportedTypes As IEnumerable(Of Type)
        Get
            Return {GetType(T)}
        End Get
    End Property

    Private Sub CheckProperties(obj As Object, ByRef serialized As IDictionary(Of String, Object))
        If obj Is Nothing Then Return

        Dim objType As Type = obj.GetType()

        For Each pi In objType.GetProperties()
            ' define serialization attribute name from '
            ' xmlelement dataannotation'
            Dim displayname As String = pi.Name
            Dim attrs() As Object = pi.GetCustomAttributes(True)
            For Each attr In attrs
                If GetType(XmlElementAttribute) = attr.GetType() Then
                    displayname = CType(attr, XmlElementAttribute).ElementName
                End If
            Next
            ' fix date format'
            If pi.PropertyType = GetType(DateTime) Then
                serialized(displayname) = CType(pi.GetValue(obj, Nothing), DateTime).ToString(_dateFormat)
            Else
                ' recursive'
                If pi.PropertyType.Assembly = objType.Assembly Then
                    CheckProperties(pi.GetValue(obj, Nothing), serialized)
                Else
                    If pi.GetValue(obj, Nothing) IsNot Nothing Then
                        serialized(displayname) = pi.GetValue(obj, Nothing)
                    End If
                End If
            End If
        Next
    End Sub

    Public Shared Function GetSerializer() As JavaScriptSerializer
        Dim serializer As New JavaScriptSerializer
        serializer.RegisterConverters({New ExtendedJavaScriptSerializer(Of T)})
        Return serializer
    End Function

End Class

答案 8 :(得分:0)

我遇到了类似的问题,我希望类 SensorReading 具有Enum属性&#39; type&#39;和&#39;单位&#39;使用Enum值的名称序列化。 (如果Enum没有显式数值,则默认结果为0)

在序列化结果看起来像这样之前:

[{"id":"0","type":0,"value":"44.00","unit":0}]

我想要的是:

[{"id":"0","type":"temperature","value":"44.00","unit":"C"}]

在下面的示例函数中,我注册了一个自定义序列化程序&#39; EnumConverter&lt; SensorReading &gt;&#39;在序列化对象之前。

public static string ToSJSon(object obj)
{
    var jss = new JavaScriptSerializer();
    jss.RegisterConverters(new[] { new EnumConverter<SensorReading>() });


    return jss.Serialize(obj);
}

这是通用的EnumConverter

public class EnumConverter<T> : JavaScriptConverter
{

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

    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
        throw new NotImplementedException(String.Format("'{0}' does not yet implement 'Deserialize", this.GetType().Name));
    }

    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {

        IDictionary<string, object> serialized = new Dictionary<string, object>();
        if (obj.GetType() == typeof(T))
        {
            if (obj.GetType().IsEnum)
            {
                serialized[obj.GetType().Name] = Enum.GetName(obj.GetType(), obj); ;
            }
            else
            {
                var sourceType = obj.GetType();
                var properties = sourceType.GetProperties();
                foreach (PropertyInfo property in properties)
                {
                    if (property.CanRead)
                    {
                        if (property.PropertyType.IsEnum)
                        {
                            var str = Enum.GetName(property.PropertyType, property.GetValue(obj, null));
                            serialized[property.Name] = str;
                        }
                        else
                        {
                            serialized[property.Name] = property.GetValue(obj, null);
                        }

                    }
                }
            }
        }

        return serialized;

    }

}

自定义序列化程序宣布它序列化T类型的对象,并在Serialize中循环所有可读属性。如果property是Enum,则将名称而不是值返回到字典。

这可以扩展到其他属性类型,而不是按照我们想要的方式序列化。

如果自定义序列化程序T恰好是Enum,我添加了一个单独的测试。然后输出Enum类的名称和它的值。结果将如下所示:

[{"id":"0","type":{"ReadingType":"temperature"},"value":"44.00","unit":{"ReadingUnit":"C"}}]

如果您打算反序列化并想知道该值属于哪种枚举类型,那么这可能是更好的输出。

答案 9 :(得分:-1)

link text 此示例有效

JavaScriptSerializer serializer = new JavaScriptSerializer();

DateTime dt = DateTime.Now;
DateTime dt1 = dt;

string jsonDateNow = serializer.Serialize(dt1);