Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable Type Hinting in WCF JSON Services

I have what should be a relatively simple question that I can't seem to find an answer for.

When WCF performs its serialization of objects, it automatically applies Type Hinting. For Json services, this results in an extra field on each complex object called __type. An object defined as:

[DataContract]
public class SomeObject
{
    [DataMember]
    public string First { get; set; }

    [DataMember]
    public string Last { get; set; }
}

Would serialize to something like:

{
    "First" : "Hello",
    "Last" : "World!",
    "__type" : "SomeObject#MyNamespace.SomeObject"
}

Normally this isn't an issue. Unfortunately when you start nesting classes into fairly large and complex structures, this results in a ton of overhead in the size of the JSON response going back to the client.

Surely there has to be a way to disable this behavior but I haven't been able to find one (neither had Rick Strahl back in 2007...but it's 2010 and I hope somebody has figured this out).

like image 853
Justin Niessner Avatar asked Sep 16 '10 19:09

Justin Niessner


3 Answers

I'm assuming you are using <enableWebScript/> in your behavior config, replace that with <webHttp defaultOutgoingResponseFormat="Json"/> and you will get nice and clean json

like image 113
JeremyWeir Avatar answered Oct 20 '22 10:10

JeremyWeir


Using the DataContractJsonSerializer is going to want to do this to support polymorphism and be able to deserialize back to a known type. NewtonSoft is a third party json serializer that won't add the __type hint. If your just serializing and not using an real advance DataContract attributes, you may want to give it a try.

like image 6
Chris Avatar answered Oct 20 '22 09:10

Chris


This did the trick for me:

[WebGet(ResponseFormat=WebMessageFormat.Json,BodyStyle = WebMessageBodyStyle.Bare)]

See steps 7 and 10 from http://dotnetdiscoveries.blogspot.com/2008/05/return-json-from-ajax-enabled-wcf.html

like image 3
vjang Avatar answered Oct 20 '22 10:10

vjang