Junior
Junior

Reputation: 11990

How to serialize datetime value in C# ASP.NET?

I am using ASP.NET MVC5 framework to build an app. I need a function to allow me to easily convert ad object to a json string.

I found this awsome class that will do exactly what I need.

using System.Web.Script.Serialization;
namespace App.Support
{
    public static class JsonHelpers
    {
        public static string ToJson(this object obj)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Serialize(obj);
        }

        public static string ToJson(this object obj, int recursionDepth)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            serializer.RecursionLimit = recursionDepth;
            return serializer.Serialize(obj);
        }
    }
}

The only issue that I am not sure how to workaround is datetime values.

after reading a list from a database with some datetime column I want to convert the list to json. When I use JsonHelper.ToJson(mylist); the datetime fields will look like this Date(1456182878660)

How can I convert that value to YYYY-MM-DD- H:i:s format? when I parse the json string using jQuery the datetime value looks like this /Date(1456182878660)/

Upvotes: 0

Views: 551

Answers (1)

RobIII
RobIII

Reputation: 8821

I would recommend Newtonsoft.Json or one of the many alternatives instead of the 'native' JavaScriptSerializer. Newtonsoft.Json (but many others as well) allow for much better control of the (de)serialization process and many also perform better. Even better: since you're doing ASP.Net, chances are the package is already installed in your project.

Upvotes: 1

Related Questions