Reputation: 15217
How can I make json.net serialize datetime field as asp.net mvc 4 did, something like
/Date(122818919)/
I want to change serializer from MVC to json.net, but keep existing serialization for some properties. Maybe there is existing converter for that?
Upvotes: 0
Views: 913
Reputation: 6876
This is really easy to do. When you new up your serializer pass a settings object to it.
JsonSerializerSettings _settings = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Error,
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
};
JsonSerializer _scriptSerializer = JsonSerializer.Create(_settings);
What I done was create a new JsonNetResult and apply it on that...
public class JsonNetResult : JsonResult
{
private static JsonSerializerSettings _settings;
private static JsonSerializer _scriptSerializer;
static JsonNetResult()
{
_settings = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Error,
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
};
_scriptSerializer = JsonSerializer.Create(_settings);
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null) throw new ArgumentNullException("context");
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;
if (this.ContentEncoding != null)
response.ContentEncoding = this.ContentEncoding;
if (this.Data == null)
return;
using (StringWriter sw = new StringWriter())
{
_scriptSerializer.Serialize(sw, this.Data);
response.Write(sw.ToString());
}
}
}
This allows your controller code to become really simple.
protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
{
return new JsonNetResult
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding,
JsonRequestBehavior = behavior,
};
}
That would allow you to do it on on all requests. If you want to change it on one property of one object the following should do the trick.
public class SomeObject
{
[Newtonsoft.Json.JsonProperty(ItemConverterType = typeof(Newtonsoft.Json.Converters.JavaScriptDateTimeConverter))]
public DateTime Time { get; set; }
}
Upvotes: 2