Krishanu Dey
Krishanu Dey

Reputation: 6406

Convert Date into JSON object in c#

I've created a C# class with a static method that convert's any object to a JSON object. I've used JavaScriptSerializar for this. Here is my code

public class JS
{
    public static string GetJSON(object obj)
    {
        JavaScriptSerializer js = new JavaScriptSerializer();
        string retJSON = js.Serialize(obj);
        return retJSON;
    }
}

I've another class that have only two property, Date & Remark. Here is my class

public class RemarkData
{
    public DateTime Date { set; get; }
    public string Remark { set; get; }
}

Now, I'm converting a object of the RemarkData class into JSON using following code

JS.GetJSON(objRemarkData);

Here is the output I'm getting

{"Date":"/Date(1389403352042)/","Remark":"Sme Remarks"}

Here is the output that I need

{"Date":1389403352042,"Remark":"Some Remarks"}

What should I do tho get that kind of output? Any help ?

Upvotes: 1

Views: 4172

Answers (3)

Muthu
Muthu

Reputation: 2685

This long number is "milliseconds since epoch". We can convert this to normal javascript date by using the following snippet as explained in another so post Converting .NET DateTime to JSON

var d = new Date();
d.setTime(1245398693390);
document.write(d);

One can also use a nice library from http://blog.stevenlevithan.com/archives/date-time-format with the following snippet ..

var newDate = dateFormat(jsonDate, "dd/mm/yyyy h:MM TT");

Upvotes: 0

Khanh TO
Khanh TO

Reputation: 48972

You could try JSON.NET, it serializes Date into ISO string.

public class JS
{
    public static string GetJSON(object obj)
    {
        string retJSON = JsonConvert.SerializeObject(obj);
        return retJSON;
    }
}

Actually, you can use it directly, don't need to wrap inside another function.

This is also how asp.net web api serializes date objects. For more information why ISO string is a good choice, check out this link http://www.hanselman.com/blog/OnTheNightmareThatIsJSONDatesPlusJSONNETAndASPNETWebAPI.aspx

Upvotes: 1

Damith
Damith

Reputation: 63065

double ticks = Math.Floor(objRemarkData.Date.ToUniversalTime() 
        .Subtract(new DateTime(1970, 1, 1))      
        .TotalMilliseconds); 
var newob = new { Date =ticks, Remark = objRemarkData.Remark};
JS.GetJSON(newob);

Upvotes: 2

Related Questions