Rick Strahl's Weblog  

Wind, waves, code and everything in between...
.NET • C# • Markdown • WPF • All Things Web
Contact   •   Articles   •   Products   •   Support   •   Advertise
Sponsored by:
West Wind WebSurge - Rest Client and Http Load Testing for Windows

JSON Serializers in .NET - not there yet


:P
On this page:

A few days ago somebody asked me why I bothered in the West Wind Ajax Toolkit with building a custom JSON parser, which is a valid question. After all Microsoft now has two separate JSON parsers in the .NET framework so why use a custom parser?

Some time ago - before the days of Microsoft Ajax 1.0 - I built my own .NET JSON serializer and deserializer, because there's was limited support for JSON serialization and more importantly deserialization available at the time. There were a few frameworks out there - including my favorite which was Anthem at the time - which included JSON serializers that could send JSON data to JavaScript clients for consumption. Generating JSON output is actually pretty straight forward as the encoding mechanisms are easy to produce even for complex and hierarchical objects from managed code. The other end - de-serialization into a specific .NET type - is considerably more difficult to do because the language format for JSON is fairly terse with many redundant symbols. Parsing JSON is no picknic especially if you want to build a parser that can validate JSON up front or during processing as invalid (and in fact, the one I built doesn't).

When I first started out on this path I used Anthem's serializer as a base line and then tacked on my own de-serializer. Right around the time that happened Microsoft released the fist builds of ASP.NET AJAX (ATLAS at the time) which also included a new JavaScriptSerializer, which I was glad to see at the time. I figured my code wouldn't be needed for too long so I didn't spend much time on making the de-serializer work perfect in all scenarios and let it be 'good enough' for now to wait for release in the .NET framework. Heck, after all deserialization of client data coming back to the server is less common than sending data, especially when talking about complex types coming back from the client. But the need quickly accelerated as we all discovered the power of building JSON style RPC service interfaces that could effectively feed data back into the front Web UI. It turned out to be a long haul to MS AJAX 1.0 and in the meantime I needed a solution and so the parser evolved.

Fast forward to today. Currently the .NET framework contains two JavaScript JSON parsers to choose from:

  • JavaScriptSerializer in System.Web.Extensions
  • DataContractJsonSerializer in System.Runtime.Serialization.Web

 

JavaScriptSerializer in System.Web.Extensions

This component is part of the ASP.NET AJAX update library in System.Web.Extensions and allows serialization and deserialization of data. The interface is pretty straight forward and works reasonably well for most data types in application scenarios. The serializer works by simply passing an object and returning a string JSON result. Type support is adequate although there are a some useful omissions.

In short you can do stuff like this:

StockServer ss = new StockServer();
StockQuote quote = ss.GetStockQuote("MSFT");
 
JavaScriptSerializer ser = new JavaScriptSerializer();
string json = ser.Serialize(quote);
 
StockQuote quote2 = ser.Deserialize<StockQuote>(json);

to serialize and then deserialize content.

At first glance this looks great - it's nice and easy but there's a small, but annoying shortcoming here: The Deserialize method is generic and so requires a type known at compile time - it can't be type variable, but has to be a type constant.

StockQuote quote2 = ser.Deserialize<StockQuote>(json);

The generic parameter must be a type constant (or typeof()) in order to work, but you can't do something like this:

Type stockType = quote.GetType();    
...
StockQuote quote2 = ser.Deserialize<stockType>(json);   // doesn't work

because generics are compiler based and create effectively overloaded method stubs for each type variation. Bummer in this case. I really hate it when APIs provide ONLY generic interfaces and no way to specify a type dynamically.

Anyway, this means that out of the gate you can't easily create dynamic routines that do things like parsing a number of parameters say to forward calls to an object dynamically as you might do to build a JSON service.

Actually - after posting a small blip on Twitter today - I got a hint from Stuart Thompson about using Reflection to provide a generic parameter at runtime. With that it's possible to access to the Deserialize method with a type variable:

public static object FromJsonString(string json, Type type)
{
    // *** Have to use Reflection with a 'dynamic' non constant type instance
    JavaScriptSerializer ser = new JavaScriptSerializer();
 
    object result = ser.GetType()
                       .GetMethod("Deserialize")
                       .MakeGenericMethod(type)
                      .Invoke(ser, new object[1] { json });
    return result;
}

It's ugly but it works for this scenario.

To make this more reusable you can create an Extension class that provides JSON features ToJson() on object and FromJson() on string along with classic static methods:

/// <summary>

/// Json Extensions based on the JavaScript Serializer in System.web
/// </summary>
public static class JsonExtensionsWeb
{
    /// <summary>
    /// Serializes a type to Json. Note the type must be marked Serializable
    /// or include a DataContract attribute. 
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static string ToJsonString(object value)
    {
        JavaScriptSerializer ser = new JavaScriptSerializer();
        string json = ser.Serialize(value);
        return json;
    }
 
    /// <summary>
    /// Extension method on object that serializes the value to Json. 
    /// Note the type must be marked Serializable or include a DataContract attribute. 
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static string ToJson(this object value)
    {
        return ToJsonString(value);
    }
 
    /// <summary>
    /// Deserializes a json string into a specific type.
    /// Note that the type specified must be serializable.
    /// </summary>
    /// <param name="json"></param>
    /// <param name="type"></param>
    /// <returns></returns>
    public static object FromJsonString(string json, Type type)
    {
        // *** Have to use Reflection with a 'dynamic' non constant type instance
        System.Web.Script.Serialization.JavaScriptSerializer ser
                = new System.Web.Script.Serialization.JavaScriptSerializer();
 
        object result = ser.GetType()
                                .GetMethod("Deserialize")
                                .MakeGenericMethod(type)
                                .Invoke(ser, new object[1] { json });
        return result;
    }
 
    /// <summary>
    /// Extension method to string that deserializes a json string 
    /// into a specific type.
    /// Note that the type specified must be serializable.
    /// </summary>
    /// <param name="json"></param>
    /// <param name="type"></param>
    /// <returns></returns>
    public static object FromJson(this string json, Type type)
    {
        return FromJsonString(json, type);
    }
 
 
    public static TType FromJson<TType>(this string json)
    {
        System.Web.Script.Serialization.JavaScriptSerializer ser
                = new System.Web.Script.Serialization.JavaScriptSerializer();
 
        TType result = ser.Deserialize<TType>(json);
        return result;
    }
}

One thing that's nice about the JavaScriptSerializer is that it works on most common .NET types and doesn't require any special object attributes. I think this is an important feature of any JSON serializer because unlike typical 'Service' interfaces often times JSON is used purely for UI services to feed data and having to specify any sort of attribute or markup contract only gets to be counter productive.

This is especially useful when used in combination with dynamic type results through anonymous types explicitly created in code or - probably more to the point - LINQ based custom results that are filtered down to only return the exact data required to the client.

Using the JavaScriptSerializer with the above extension classes allow you do the following with an anonymous type:

// *** Can serialize anonymous types with JavaScriptSerializer            
var valueDyn = new
{
    Name = "Rick Strahl",
    Entered = DateTime.Now.AddDays(-10),
    Number = 100.22M
};
json = valueDyn.ToJson();
this.WriteValue(json);

Note that while you can Serialize an anonymous type, you cannot Deserialize it because anonymous types don't have a parameterless constructor. However, if you have a concrete type that matches the object signature of the object serialized into JSON you can still potentially import the data. So you can serialize just the data you need on the client, but you can deserialize back into the full  originating type.

Another issue: JavaScriptSerializer chokes on circular references which are common in data models (like LINQ to SQL).

Anyway - this dynamic behavior is quite useful and is a big plus of this serializer over the DataContractSerializer as we'll see in a minute.

The JavaScriptSerializer has another problem though: It's now marked obsolete and according to the documentation and compiler error we're supposed to use DataContractJsonSerializer for Json serialization. I think it was a good idea that JSON moved into a more generic portion of the .NET framework, but unfortunately the DataContractJsonSerializer has even more restrictive interface than JavaScriptSerializer.

So in summary:

Pros:

  • Easy to use
  • Doesn't require any marker interfaces to serialize objects

Cons:

  • API requires static types for Deserialization (generic method only)
  • Dynamic Types require Reflection and extra code
  • Class has been deprecated by Microsoft
  • Doesn't work with a few common data structures
  • Chokes on circular references


DataContractJsonSerializer

DataContractJsonSerializer is part of .NET 3.5 WCF extensions and lives in System.ServiceModel.Web. The primary purpose of this new Serializer - and it shows - is to handle the JSON serialization support for the .NET 3.5 WCF Http extensions which provide REST and AJAX services that are specifically geared to the Web model. As such the WCF 3.5 REST and AJAX services are quite at odds with the rest of WCF in that they don't interoperate really as smoothly as other service types that can usually just tweak a few configuration settings and enjoy the same behavior for various different protocols. The difference here is that the HTTP protocols are highly specialized to REST and AJAX scenarios which doesn't fit with the SOAP style messaging normally used in WCF. IOW, the HTTP REST/AJAX services are the odd man out when it comes to WCF functionality.

The DataContractSerializer clearly is geared towards serving the needs of the WCF platform as it uses and even requires use of attributes to adorn objects and members to allow them to be serialized and deserialized. And therein is probably the biggest downfall of the DataContractJsonSerializer: It requires WCF compatible types and attributes.

The model for serialization is also a bit more verbose than the JavaScriptSerializer, although it's nothing that a small wrapper method can't fix easily. Here's how to serialize and deserialize:

StockServer ss = new StockServer();
StockQuote quote = ss.GetStockQuote("IBM");
 
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(StockQuote));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, quote);
string json = Encoding.Default.GetString(ms.ToArray());
 
 
// *** Deserialize
ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
ser = new DataContractJsonSerializer(typeof(StockQuote));
StockQuote quote2 = ser.ReadObject(ms) as StockQuote;
ms.Close();
 

The DataContractJsonSerializer is a little more work to use than the JavaScriptSerializer as it works off input streams, but it's still pretty simple. The code used can be easily abstracted and the serializer works well as long as you're working off serializable types.

For completeness here's the same extension class using the DataContractSerializer as the base converter:

public static class JsonExtensions
{
    /// <summary>
    /// Serializes a type to Json. Note the type must be marked Serializable
    /// or include a DataContract attribute. 
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static string ToJsonString(object value)
    {
        DataContractJsonSerializer ser = new DataContractJsonSerializer(value.GetType());
        MemoryStream ms = new MemoryStream();
        ser.WriteObject(ms, value);
        string json = Encoding.Default.GetString(ms.ToArray());
        return json;
    }
 
    /// <summary>
    /// Extension method on object that serializes the value to Json. 
    /// Note the type must be marked Serializable or include a DataContract attribute. 
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static string ToJson(this object value)
    {
        return ToJsonString(value);
    }
 
    /// <summary>
    /// Deserializes a json string into a specific type.
    /// Note that the type specified must be serializable.
    /// </summary>
    /// <param name="json"></param>
    /// <param name="type"></param>
    /// <returns></returns>
    public static object FromJsonString(string json, Type type)
    {
        MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
        DataContractJsonSerializer ser = new DataContractJsonSerializer(type);
        object value = ser.ReadObject(ms);
        ms.Close();
        return value;
    }
    /// <summary>
    /// Extension method to string that deserializes a json string 
    /// into a specific type.
    /// Note that the type specified must be serializable.
    /// </summary>
    /// <param name="json"></param>
    /// <param name="type"></param>
    /// <returns></returns>
    public static object FromJson(this string json, Type type)
    {
        return FromJsonString(json,type);
    }
}

 

The big problem with DataContractSerializer is that it only works off serializable types. You need to either have the type marked with a [DataContract] and explicit [DataMember] values or the type must be marked as [Serializable]. Both might make good sense for WCF style service scenarios but for JSON messages sent from Web applications this requirement is pretty much a deal killer. This also means no anonymous type support so if you want to use this serializer with data returned from LINQ queries you'll have to make sure you return full entities and these entities are marked up with the appropriate attributes. Yechh...

Pros:

  • Microsoft's official JSON parser
  • Works with dynamic types
  • Updated and integrated with WCF
  • Deals with circular references (also some control over depth of serialization)

Cons:

  • Requires marked up types - Serializable or DatContract/DataMember required
  • Requires a number of assembly refs

So where does that leave us?

As I mentioned at the outset, the two parsers are workable, but both have their issues. Clearly Microsoft is pushing towards DataContractJsonSerializer, but with it come some limitations that make it somewhat unusable in certain scenarios. For me the inability to push results from dynamic LINQ queries to the client is proving to be fatal.

JavaScriptSerializer works well enough with a few exceptions, but the problem here is the the Obsoleting by Microsoft. Also I have a fair bit of legacy code that uses DataSets and DataTables fed back from list based data of business objects and it's very useful to feed that to the client as object arrays. This will change eventually, but in the meantime this old code needs to continue to work with this data. This can be done with JavaScriptSerializer by creating special TypeResolvers but it's a  pain - this should just be built in even if some functionality is one way.

The other issue is that both serializers are using some proprietary formats for things like dates. It's not a bad solution as long as you're running MS AJAX or a compatible framework (my toolkit also supports those formats), but if a client passes data in a different format (say new Date() or the new 'suggested' ISO date literal) the deserializers choke, which is problematic when dealing with non-.NET based client JSON serialization.

For me - it means I can't switch to the built in JSON parsers, so for the time being I'm sticking with my existing home grown parser which addresses all of these issues. But, maintenance of a parser is always a pain especially as standard changes and additions are likely to occur. JavaScript serialization is pretty trivial, but the deserialization can get pretty gnarly quickly especially if validation is required :-{. I'd much rather use something out of the box. So I'm hoping that Microsoft will step up and provide something that's a little more light handed than the DataContractJsonSerializer.

There are also several other libraries out there including JSON.Net, Ajax.Net Pro, Anthem.Net and several others that also provide JSON services with varying degrees of flexibility as is the West Wind Ajax Toolkit where you can find the above mentioned free standing JSON parser.

I use JSON serialization daily and for the moment at least I'm glad that I have a custom parser in place because I have more control over the process and can allow any kind of content to go through the parser and format it as needed easily. In the end that's what counts...

Posted in AJAX  ASP.NET  JavaScript  

The Voices of Reason


 

Bertrand Le Roy
August 04, 2008

# re: JSON Serializers in .NET - not there yet

All good points, thanks Rick. I happen to have a pending work item on an overload of deserialize that takes a dynamic type. I'd also like to get the obsolete attribute removed (but that may be easier said than done). Not sure which types you're referring to when you say some common data structures don't work. Can you elaborate?
On dates, new Date() is *not* JSON so I think it's normal that it chokes. Now, ISO dates are still expressed as strings (so that JSON remains valid JS) so the parser won't choke on that, it will just deserialize as a string. I understand that may be a problem if you're deserializing to a specific type that has DateTime properties though, and I'll see what we can do in that case (we should be able to try to parse the string if we know for sure the target is a date).

Rick Strahl
August 04, 2008

# re: JSON Serializers in .NET - not there yet

@Bertrand - thanks for the feedback. In fact I was going to bug you privately about this but figured you'd read it here anyway :=}. Getting another non-generic method on JavaScript Serializer would be useful.

One more issue (that I haven't tested recently though) was that the Serializer would choke on recursive object refs or very deep nesting (as does mine <g>) - this was one place where the DataContractSerializer works better. Maybe this has been fixed though - I think this was prior to .NET 3.5 releasing.

As to types that I care about - class ADO.NET structures for some legacy code. There was converter in Futures for this, but this is still a common scenario for a number of active apps. That's DataSet,DataTable,DataRow serialization which has been very useful.

As to the date deserializing - it would be great if other syntax could also be supported. Several clients put out new Date(ms) syntax and that would be useful to fix. ISO date format when it moves closer to standard. I don't think that it gets encoded as string. JSON2 (which I believe is following the proposed standard isn't string encoding. The MS AJAX syntax works well enough if you have a compliant parser on both ends (which I typically do), but people are bugged me constantly about this so I added support for the three most common formats on the parsing and output end (flaggable).

Kevin Dente
August 04, 2008

# re: JSON Serializers in .NET - not there yet

DataContractSerializer was changed in .NET 3.5SP1 to remove the requirement for special attributes. Have you checked to see if that's true for the JSON version as well?

Also, according to ScottGu's comment here:
http://www.aaronlerch.com/blog/2008/05/27/first-thoughts-on-aspnet-mvc-preview-3/#comments

JavaScriptSerializer is being undeprecated for SP1.

Rick Strahl
August 04, 2008

# re: JSON Serializers in .NET - not there yet

@Kevin - DataContractSerializer was changed so it doesn't require this? Wow, that would be a major change given that everything is supposed to be about contracts. I can just see the Service Wonks having a fit on that one, but probably a good idea especially if this is the case for the DataContractJsonSerializer.

As to JavaScriptSerializer that's great too - just a little surprised given Bertrand's earlier response.

I haven't installed SP1 to date since I've been on the road and didn't want to deal with the headaches of possibly repaving my machine (apparently a lot of folks ended up that way). Sp1 should show up soon in RTM though and then we can check it out.

If DCJS works without required attributes it would be much improved.

Scott Allen
August 04, 2008

# re: JSON Serializers in .NET - not there yet

@Kevin - The DataContractJsonSerializer still doesn't like anon types in SP1. :(

Zack Owens
August 04, 2008

# re: JSON Serializers in .NET - not there yet

My real test of the validity of a JsonDeSerializer is whether it can deserialize a generic list. So far only AjaxPro can do it for me.

Rick Strahl
August 04, 2008

# re: JSON Serializers in .NET - not there yet

@Zack - Generic lists work fine with JavaScriptSerializer as it does with the West Wind parser. I suspect it's not the list itself that's the issue, but what the data type of the list items.

Bertrand Le Roy
August 04, 2008

# re: JSON Serializers in .NET - not there yet

Don't be surprised, I just need to remove the foot from my mouth. It indeed seems to be gone and I vaguely remember someone mentioning that now... ooops

Bertrand Le Roy
August 05, 2008

# re: JSON Serializers in .NET - not there yet

Oh, and I quilckly checked JSON2, and dates *are* serialized as strings. It wouldn't make sense for JSON not to be valid JS.

Andrey Shchekin
August 06, 2008

# re: JSON Serializers in .NET - not there yet

Json Serialization API is one of the worst Microsoft libraries I've seen. The worst thing is that you can not just override some converters to use alternative libraries -- if you are calling Web Service from JSON, you will have to deal with all its quirks.

For example, all custom types must serialize to IDictionary<string, object>, there is no way to serialize custom type to number or string. Same is true for deserialization. Also, Microsoft keeps ignoring their best creation -- System.ComponentModel, which actually provides an extensible way to create a type that does not have a default constructor.

I have a feeling that my team can solve any problem, _except_ if it is caused by MS serialization, in which case the solution is almost always a hack.

Brian C
August 06, 2008

# re: JSON Serializers in .NET - not there yet

JSON.NET, an open source project from James Newton-King, is my favorite after dealing with the nightmare of DataContractJsonSerializer.

http://james.newtonking.com/pages/json-net.aspx

James Newton-King
August 06, 2008

# re: JSON Serializers in .NET - not there yet

Rick you should check out Json.NET in more detail.

Supports generic lists, circular references, anonymous types, has multiple options for date serialization (MS method, JavaScript Date constructor, ISO 8601 formatted string), and lots lots more. I've put a lot of time into making the serializer as powerful and flexible as possible.

Stephen
August 06, 2008

# re: JSON Serializers in .NET - not there yet

I too am a HUGE fan of Newton's JSON class..... it works so well with jQuery's getJSON method :-)

Rick Strahl
August 06, 2008

# re: JSON Serializers in .NET - not there yet

@James - yes JSON.Net looks nice and I have used it on a few occasions related to some project work.

The big problem I have with it is that it's an external package. I need to be able to package the code up and redistribute it and using third party code for this tends to be problematic due to licensing or alternate code bloat. Ideally I would like this stuff to be in the framework as it IMHO should be given the importance of AJAX these days.

In the meantime I'm using my homegrown parser for this reason alone and frankly I've not run into any issues myself although I have no doubts there are scenarios where it breaks (circular refs being one although that's fairly easy to fix).

Keep up the good work though - if it wasn't for the redist requirement I would have long switched horses. Maintaining parser code is a pain and I'd rather leave that to somebody specialized in that space :-}...

Andrey Shchekin
August 06, 2008

# re: JSON Serializers in .NET - not there yet

@James -- your serializer is great, and while my team, used it we never had problems with serialization. The problem is, if I am calling a Web Service from ASP.NET AJAX, MS solution is going to be used, unless I rewrite the entire ScriptHandlerFactory.

Rick Strahl
August 06, 2008

# re: JSON Serializers in .NET - not there yet

@Andrey - the server processing part is pretty easy to handle and it's fairly easy to remove the MS AJAX stack on that end. I have a simple handler implementation that works either through a very efficient handler or through 'real' page/control methods.

Once you have a reliable JSON parser the callback routing is pretty trivial to set up. If you're interested you can take a look at the CallbackMethodProcessor class in the West Wind Toolkit which does all of this with a few lines of code.

JayRock also provides this and it's also light weight and easier to manage than MS AJAX.

But people will gravitate to 'what's in the box'. Even as a tool builder I end up there because avoiding external code is always a priority. I suspect many app developers feel the same way and that's why I'm hoping that more improvements will come in the built-in parsers.

Code Monkey Labs
August 08, 2008

# Weekly Web Nuggets #24

Probably the biggest news of the week is that SQL Server 2008 RTM'd this week, and is already available on MSDN. A word of warning...if you have Visual Studio 2008 installed, you're better off waiting until Monday when SP1 for Visual Studio 2008 ships. General The Onion Architecture Part 3 : In this...


Andrey Shchekin
August 09, 2008

# re: JSON Serializers in .NET - not there yet

@Rick, thanks, I was sure it was hard to do for asmx Web Services.
Now I feel somewhat stupid.

I'll definitely look at it again, that could solve a lot of pain points for us.

As for callbacks, I have my own Newtonsoft-based implementation, but I do not like to request Page/Control methods for callbacks.

# Serialize Links

Tagged your site as serialize at iLinkShare!

Code Monkey Labs
February 22, 2009

# Weekly Web Nuggets #24

Probably the biggest news of the week is that SQL Server 2008 RTM'd this week, and is already available on MSDN. A word of warning...if you have Visual Studio 2008 installed, you're better off waiting until Monday when SP1 for Visual Studio 2008 ships. General The Onion Architecture Part 3 : In this...


Todd Meinershagen
April 17, 2009

# re: JSON Serializers in .NET - not there yet

After reading this article, I am not sure that others will be interested in using the DataContractJsonSerializer class. It sounds like there are a lot of other options.

However, if you are interested, I did have to make a correction to the code that Rick provided. He missed using the 'this' keyword in the first parameter in order for the extensions to be recognized off of the string object. I have also made the FromJsonString method generic so that it will return an object of the type that you specify.

Hope this helps someone out there.

/// <summary>
/// Serializes a type to Json. Note the type must be marked Serializable
/// or include a DataContract attribute.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string ToJsonString(this object value)
{
var ser = new DataContractJsonSerializer(value.GetType());
var ms = new MemoryStream();
ser.WriteObject(ms, value);
string json = Encoding.Default.GetString(ms.ToArray());
return json;
}

/// <summary>
/// Deserializes a json string into a specific type.
/// Note that the type specified must be serializable.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="json">The json.</param>
/// <returns></returns>
public static T FromJsonString<T>(this string json) where T:class
{
var ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
var ser = new DataContractJsonSerializer(typeof(T));
object value = ser.ReadObject(ms);
ms.Close();
return value as T;
}

# Stockquote Bookmarks

Bookmarked your page with keywords stockquote!

tsmith
November 19, 2009

# re: JSON Serializers in .NET - not there yet

Does the DataContractJsonSerializer deal with circular references?

Rick Strahl
November 19, 2009

# re: JSON Serializers in .NET - not there yet

@tsmith - The DataContract Serializer can handle circular references yes. The JavaScript serializer chokes on them.

Srihari
February 24, 2010

# re: JSON Serializers in .NET - not there yet

Hi,

I am building an RESTFull WCF service. My data contract types having the DateTime fields. If I assign the DateTime value of the field to DateTime.MinValue, the format of DateTime showing in the rendered output for Json is "Date(-62135596800000)" . In rest of the cases it is showing the format "2007-10-30T06:56:00"

I tested the Json output with different dateTime values. Those are,

1. If DateTime field value is "DateTime.Now", then Json output format is Date(1266960616682-0800)
2. If DateTime field value is "DateTime.MinValue", then Json output format is Date(-62135596800000)
3. if we asssign any date explicitly, the json output format is "2007-10-30T06:56:00"

I want single DateTime format through out my json output. Could you help me on this.

Thanks,
Srihari

The Accidental Geek
October 16, 2010

# DotNetNuke Tips and Tricks #22: ToJson or not ToJson

DotNetNuke Tips and Tricks #22: ToJson or not ToJson

West Wind  © Rick Strahl, West Wind Technologies, 2005 - 2024