1

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 ?

Krishanu Dey
  • 6,326
  • 7
  • 51
  • 69
  • You will probably register your own `DateTime` converter. Does answers to this question helps you: http://stackoverflow.com/questions/1341719/custom-javascriptconverter-for-datetime? – Konrad Kokosa Jan 11 '14 at 01:32
  • That example is converting date in `dd/mm/yyyy` or some regular format that I specify. But how the date is converted into `1389403352042` this type of value? – Krishanu Dey Jan 11 '14 at 01:41
  • It should be `DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond` – Konrad Kokosa Jan 11 '14 at 01:46

3 Answers3

2
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);
Damith
  • 62,401
  • 13
  • 102
  • 153
  • How do you get the JSON date string "/Date(1389403352042)/" to a DateTime object though? Just string operations to the the numeric value, and go from there? – Adrian K Apr 24 '17 at 21:33
1

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

Khanh TO
  • 48,509
  • 13
  • 99
  • 115
0

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");
Community
  • 1
  • 1
Muthu
  • 2,675
  • 4
  • 28
  • 34