Is there a way to return DateTime in ISO format from a asp .net web method instead of JSON format?
Asked Answered
I

2

6

Currently the web methods or most of the methods in classic asp .net serializes using system.web.script.serialization.javascriptserializer class and this returns the javascript object's datetime members with values such as

"/Date(number of ticks)/"

. I understand this is an infamous problem and most people suggest using some kind of converters after we receive the data or return the data as string instead of objects.

For example the class

public class Person
{
    public String Name { get; set; }
    public int Age { get; set; }
    public DateTime DOB { get; set; }
}

if returned via a System.Web.Services.WebMethod with a [ScriptMethod(ResponseFormat = ResponseFormat.Json)] decoration, the response will be returned as below in result.d

{Name:"Steve", Age:30, DOB:"/Date(1249335477787)/"};

And we need to apply some code to convert the DOB into ISO format or some other acceptable format.

But I am just trying to see if some one has done some kind of response tweaking or using an over-ridden class to return the DateTime values from web methods. Is there a way to over-ride the javascriptserializer's functionality and use it in asp .net web methods so that it returns the date directly in ISO format? I am aware that it can be done in asp .net MVC in a few ways.

Is the same can be done in asp .net web form's web methods? That would save a lot of code and bugs as well :)

Ivyiwis answered 14/9, 2015 at 11:3 Comment(3)
you can write your own custom json serializier using newtonsoftAmbriz
yes, but how do I tell the WebMethod to use this new custom serializer to return the object. I do not want to return it as a string as well :(Ivyiwis
ISO is the JSON format. Are you using the (deprecated) JavaScriptSerializer perhaps?Tarrance
I
3

I found a trick from http://blog.icanmakethiswork.io/2012/04/beg-steal-or-borrow-decent-javascript.html.

This is to replace the JsonSerializer's own date serializer and use the custom date serializer.

  • Override the System.Web.Script.Serialization.JavaScriptConverter
  • Update web.config section to apply this to whole project or use RegisterConverters function for using it locally

This is able to return me back a ISO formatted date time and I am also able to pass this inside moment js for manipulations inside javascript.

Ivyiwis answered 15/9, 2015 at 10:28 Comment(1)
the link is broken, updated links: source 1 source 2Samuelson
A
-3

You can easily declare the response type in webmethod. Also you can use custom serializer as described in this link or see follwoing code on how to format a date:

class DualDateJsonConverter : JsonConverter
{

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {

        JObject result = new JObject();

        DualDate dd = (DualDate)value;

        result.Add("DateOne", JToken.FromObject(dd.DateOne.ToString("MM.dd.yyyy")));
        result.Add("DateTwo", JToken.FromObject(dd.DateTwo));
        result.WriteTo(writer);
    }

    // Other JsonConverterMethods
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(DualDate);
    }

    public override bool CanWrite
    {
        get
        {
            return true;
        }
    }
    public override bool CanRead
    {
        get
        {
            return false;
        }
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}
 Context.Response.ContentType = "application/json";
 Context.Response.Write(response);
Ambriz answered 14/9, 2015 at 11:23 Comment(8)
I think response type is already the right one, what OP doesn't like is format for dates...Zaibatsu
@AdrianoRepetti so does it mean that you can devote my answer? did you completely read my answer ?Ambriz
FYI (for what it matters) I didn't downvote your answer but yes I completely read it and even after 2nd read I don't understand what's response type has to do with question...Zaibatsu
@AdrianoRepetti A quote from the question comment "yes, but how do I tell the WebMethod to use this new custom serializer to return the object. I do not want to return it as a string as well :( "Ambriz
AFAIK changing content type won't affect how JavaScript serializer convert dates (and it must be a string if he wants ISO format). OP may clarify thisZaibatsu
Neither this or the linked question solve the problem - how to return an ISO formatted date. Replacing the deprecated JavaScriptSerializer with Json.NET is a far better answer anyway. Web API already uses it and the new MVC will use it as well.Tarrance
@PanagiotisKanavos it uses asp.net webmethod, did you even consider the question?Ambriz
Yes, and that doesn't matter either. JavaScriptSerializer is deprecated. It doesn't even support the standard date format. Json.NET is the most common Json serializer, used in ASP.NET itself. In fact, this question could be closed as duplicate of many others and the answer is always: Move to Json.NETTarrance

© 2022 - 2024 — McMap. All rights reserved.