0

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?

asked Nov 5, 2013 at 17:44

1 Answer 1

2

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; }
 }
answered Nov 5, 2013 at 17:54

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.