smiggleworth
smiggleworth

Reputation: 644

JSON.NET Serialize Date

I would like to serialize my date to be in a specific format but I can't get my act together.

I tried building a nice little class but the output gets wrapped in quotes, which doesn't work.

I'd like the JSON to look like this...

{ 
    date : new Date(2013, 8, 30) 
}

but I get this...

{
    date: "new Date(2013, 8, 30)" 
}

my class

public class DateCell : ChartCell
{
    [JsonIgnore]
    public DateTime Value { get; set; }

    [JsonProperty(PropertyName = "date")]
    public override object DataValue
    {
        get
        {
            return string.Format("new Date({0}, {1}, {2})", this.Value.Year, this.Value.Month - 1, this.Value.Day);
        }
    }
}

Upvotes: 2

Views: 2000

Answers (1)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241563

There's a difference between a JavaScript Object and JSON. What you described might be valid in a JavaScript object, but it is not valid JSON. JSON does not allow the representation that you are asking for.

In JSON a value can only be one of the following:

  • A string, such as "abc"
  • A number, such as 123 or -12.34
  • A literal value of true, false, or null
  • An array of other valid values, such as [1,"a",true]
  • Another JSON object, such as { a: 1, b: "abc" }

It cannot just be a JavaScript Object, or any other arbitrary JavaScript. See the spec at json.org.

Passing a Date object constructor would not make any sense, as JSON is a general purposed serialization format, and Date is a JavaScript native class. How would you expect non-JavaScript code to interpret this?

While there is no specific date or time format defined by the JSON standard, the de facto standard is the ISO 8601 format. Your DateTime would look something like "2013-09-30T00:00:00". There are other ways to serialize a date, but they are not as uniform or popular.

In JSON.Net, the ISO 8601 format is the default. So you don't need to do anything special other than just to serialize your object with its original properties.

public class DateCell : ChartCell
{
    public DateTime Value { get; set; }
}

UPDATE

Since you said in comments that you are passing this to Google Charts, it appears from their reference that they are using a nonstandard format that looks like the Date constructor, but has omitted the new keyword. Why they do this, I'm not sure, but you should be able to modify your original code as follows:

public class DateCell : ChartCell
{
    [JsonIgnore]
    public DateTime Value { get; set; }

    [JsonProperty(PropertyName = "date")]
    public override object DataValue
    {
        get
        {
            return string.Format("Date({0},{1},{2})", this.Value.Year, this.Value.Month - 1, this.Value.Day);
        }
    }
}

Upvotes: 4

Related Questions