By Robert

2009-03-09 17:59:01 8 Comments

Every object I return from a WebMethod of a ScriptService is wrapped into a JSON object with the data in a property named d. That's ok. But I don't want the additional __type property to be served to the client, since I do manual processing with jQuery.

Is it possible?


@Muthupandi Thiruvadi 2019-08-05 00:45:22

var settings = new DataContractJsonSerializerSettings();
settings.EmitTypeInformation = EmitTypeInformation.Never;
DataContractJsonSerializer serializerInput = new DataContractJsonSerializer(typeof(Person), settings);
var ms = new MemoryStream();
serializerInput.WriteObject(ms, personObj);
string newRequest = Encoding.UTF8.GetString(ms.ToArray());

@Alex Pandrea 2019-03-27 15:42:56

In addition to @sean 's answer of using JavaScriptSerializer .

When using JavaScriptSerializer and marking the method's ResponseFormat = WebMessageFormat.Json, the resulting response has double JSON encoding plus that if the resulting response is string, it will be plced bweteen double quotes.

To avoid this use the solution from this excellent answer to define the content type as JSON (overwrite) and stream the binary result of the JavaScriptSerializer.

The code sample from the mentioned answer:

public Stream GetCurrentCart()
    //Code ommited
    var j = new { Content = response.Content, Display=response.Display,
    var s = new JavaScriptSerializer();
    string jsonClient = s.Serialize(j);
    WebOperationContext.Current.OutgoingResponse.ContentType =
        "application/json; charset=utf-8";
    return new MemoryStream(Encoding.UTF8.GetBytes(jsonClient));

JavaScriptSerializer is in the System.Web.Script.Serialization namespace found in System.Web.Extensions.dll which is not referenced by default.

@John Morrison 2009-04-22 16:09:14

I found that if I make the default constructor of my class that my webmethod returns anything other than public it will not serialize the __type:ClassName portion.

You may want to declare your default constructor protected internal ClassName() { }

@Laramie 2010-08-09 21:32:01

I'm not getting this result, though I'm returning an array of objects. Not sure if this is the issue.

@Catch22 2010-11-09 15:47:16

Worked like a charm. The simple addition of "protected internal ClassName(){} " more than halved the amount of data in the response json object.

@Groxx 2011-03-21 22:18:18

Any solutions for if you can't make it non-public, and your object comes from a different assembly so it can't be internal? I didn't have __type for the longest time, and now it's cropping up occasionally, even though I've defined my own JavaScriptConverter :/

@Naor 2011-04-03 00:33:48

@Catch22: How does it halved the amount of data in the response json object?? how many objects and how long is you __type??

@Catch22 2011-04-04 08:21:08

@Naor: My JS object contained an array with about 1000 simple objects with two properties (ID, Name). Then is added (1000 times), that about doubles the amount of data being transferred.

@Andrew Gee 2012-07-06 12:38:14

This isn't working for me. Can someone post some sample code?

@Mr. Pumpkin 2012-07-07 03:09:48

For me it also doesn't work... still have this __type property.

@Alex Pandrea 2019-03-27 14:36:47

could not reproduce that behaviour either

@Liran Barniv 2018-11-05 20:52:44

Here is a way around that

    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public void Status()
        MyObject myObject = new MyObject(); // Your class here
        var json = Newtonsoft.Json.JsonConvert.SerializeObject(myObject);


@Stephen Kennedy 2010-10-01 13:33:31

John's solution didn't work for me as the type I'm returning is in a seperate DLL. I have full control over that DLL but I can't construct my return type if the constructor is internal.

I wondered if the return type being a public type in a library might even be the cause - I've been doing a lot of Ajax and not seen this one before.

Quick tests:

  • Temporarily moved the return type declaration into App_Code. Still get __type serialised.

  • Ditto and applied the protected internal constructor per JM. This worked (so he gets a vote).

Strangely I don't get __type with a generic return type:

public static WebMethodReturn<IEnumerable<FleetObserverLiteAddOns.VehicleAddOnAccountStatus>> GetAccountCredits()

The solution for me, however, was to leave my return type in the DLL but change the WebMethod return type to object, i.e.

public static object ApplyCredits(int addonid, int[] vehicleIds) 

instead of

public static WebMethodReturn ApplyCredits(int addonid, int[] vehicleIds)

@Etherman 2015-03-08 10:21:25

My 2 cents, however late in the day: as others have mentioned, there seem to be two ways to prevent the "__type" property:

a) Protect the parameterless constructor

b) Avoid passing the class in as a parameter to a web method

If you never need to pass the class as a parameter then you can make the constructor "protected internal". If you need to create an empty object then add in a factory method or some other constructor with a dummy parameter.

However, if you need to pass the class as a parameter to a web method then you will find that this will not work if the parameterless constructor is protected (the ajax call fails, presumably as the passed in json data cannot be deserialized into your class).

This was my problem, so I had to use a combination of (a) and (b): protect the parameterless constructor and create a dummy derived class to be used exclusively for parameters to web methods. E.g:

public class MyClass
    protected internal MyClass() { }
    public MyClass(Object someParameter) { }

// Use this class when we need to pass a JSON object into a web method
public class MyClassForParams : MyClass
    public MyClassForParams() : base() { }

Any web method that need to take in MyClass then uses MyClassForParams instead:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public MyClass DoSomething(MyClassForParams someObject)
    // Do something with someObject
    // Maybe return a MyClass object

@Art Kg 2012-10-03 19:18:41

In addition to John Morrison's advice on internal or protected internal constructor in your DataContract class, which works amazingly well for web services and majority of WCF, you might need to make an additional change in your web.config file. Instead of <enableWebScript/> element use <webHttp/> for your endpointBehaviors, e.g.:

  <behavior name="MyServiceEndpoint">

@ClearCloud8 2012-10-17 22:31:07

I think I have narrowed down the root cause of the mysterious appearing "__type" !

Here is an example where you can recreate the issue.

[WebService(Namespace = "")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Test : System.Web.Services.WebService
    public class Cat
        public String HairType { get; set; }
        public int MeowVolume { get; set; }
        public String Name { get; set; }

    public String MyMethodA(Cat cat)
        return "return value does not matter";

    public Cat MyMethodB(String someParam)
        return new Cat() { HairType = "Short", MeowVolume = 13, Name = "Felix the Cat" };

Here is the key part!

Simply because MyMethodA() exists in this same .asmx file and takes the class Cat as a parameter.... the __type will be added to the JSON returned from calling the other method: MyMethodB().

Even though they are different methods!!

My theory is as follows:

  1. When writing web services like this, Microsoft's code automatically hooks up the JSON serializing/deserializing behavior for you since you used the correct attributes, like [WebMethod] and [ScriptService].
  2. When this auto-magic Microsoft code executes, it finds a method that takes in Cat class as a parameter.
  3. It figures... oh... ok.... well since I will be receiving a Cat object from JSON.... therefore... if I ever return a Cat object as JSON from any method in the current web service class... I will give it a __type property so it will be easy to identify later when deserializing back to C#.
  4. Nyah-hahahaha...

Important Take-Away Note

You can avoid having the __type property appear in your generated JSON by avoiding taking in the class in question (Cat in my case) as a parameter to any of your WebMethods in your web service. So, in the above code, simply try modifying MyMethodA() to remove the Cat parameter. This causes the __type property to not be generated.

@eselk 2013-02-04 23:09:19

This was my issue also. I had a function that took the class as a param and another that returned it. Once I removed the function that took the class on input, the __type was gone. So for me, I'm going to make 2 versions of any classes that need to go both directions, one for requests and one for responses. This way I don't get the extra __type overhead.

@Brett Veenstra 2012-10-12 16:51:58

If you're using ServiceStack.Text JSON Serializer you just need to:

JsConfig.ExcludeTypeInfo = true;

This functionality was automatically added back in v2.28, but the code above keeps that out of the serialization. You can also change this behavior by Type with:

JsConfig<Type>.ExcludeTypeInfo = true;

@Michael 2012-05-22 05:09:05

A bit late to the thread but here goes.

We had the same issue when the property being added to the json string was a List<T>. What we did was add another property which was an array of T, something like.


public List<Person> People { get; set; }


public List<Person> People { get; set; }

[DataMember(Name = "People")]
public Person[] Persons {
    get {
        return People.ToArray();
    private set { }

While not an ideal solution, it does the trick.

@Adam 2011-11-24 03:02:57

Pass in null for the JavaScriptTypeResolver and the __type will not be serialized

JavaScriptSerializer serializer = new JavaScriptSerializer(null);
string json = serializer.Serialize(foo);

@tom_mai78101 2017-01-31 12:57:18

Tried all of the above solutions. Still didn't work for me.

@Mironline 2010-03-03 19:54:50

I not sure this a good solution , but if you use the library, you can ignore some properties by adding [JsonIgnore] attribute.

@Dhaval Patel 2013-10-05 20:01:00

Yes Mironline, it's a Good Solution. I personally use it and I thought best option to ignore the attribute is [jsonIngore],Thanks for it

@dlchambers 2011-06-14 20:38:40

This is a bit of a hack, but this worked for me (using C#):

s = (JSON string with "__type":"clsname", attributes)
string match = "\"__type\":\"([^\\\"]|\\.)*\",";
RegEx regex = new Regex(match, RegexOptions.Singleline);
string cleaned = regex.Replace(s, "");

Works with both [DataContract] and [DataContract(Namespace="")]

@Baptiste Pernet 2011-10-20 14:25:59

I -1 because this is so terrible to advice someone to do that, that it is better to say nothing.

@Darko Romanov 2013-10-17 15:40:58

what language is this: s = (JSON string with "__type":"clsname", attributes) ??

@Jonathan Sayce 2010-12-19 11:18:52

I've been trying some of these suggestions with a .NET 4 WCF service, and they don't seem to work - the JSON response still includes __type.

The easiest way I've discovered to remove the type-hinting is to change the endpoint behaviour from enableWebScript to webHttp.

    <behavior name="MapData.MapDataServiceAspNetAjaxBehavior">
      <webHttp />

The default enableWebScript behaviour is required if you're using an ASP.NET AJAX client, but if you're manipulating the JSON with JavaScript or jQuery then the webHttp behaviour is probably a better choice.

@vlad259 2011-09-17 23:45:12

That is the only thing that works for me in a .Net 4 web service. Very useful, thanks.

@Domi.Zhang 2012-01-16 09:24:22

How wonderful of this way, the 'd' keyword has been removed at the same time. Thanks a lot.

@andersh 2013-07-24 12:58:49

I also had to set message format explicitly: [WebGet(ResponseFormat = WebMessageFormat.Json)]

@WynandB 2015-05-21 04:10:42

^ I also had to specify defaultOutgoingResponseFormat="Json" or automaticFormatSelectionEnabled="true" after switching from enableWebScript to webHttp.

@Yasin Kilicdere 2015-11-15 23:05:32

This worked for me but, /jsdebug is lost now. If you are using asp:ScriptManager to generate js stubs this is no good.

@Laramie 2010-08-09 21:50:38

This should solve it.

In the private SerializeValue method of JavaScriptSerializer in System.WebExtensions.dll, the __type is added to an internal dictionary if it can be resolved.

From Reflector:

private void SerializeValue(object o, StringBuilder sb, int depth, Hashtable objectsInUse)
    if (++depth > this._recursionLimit)
        throw new ArgumentException(AtlasWeb.JSON_DepthLimitExceeded);
    JavaScriptConverter converter = null;
    if ((o != null) && this.ConverterExistsForType(o.GetType(), out converter))
        IDictionary<string, object> dictionary = converter.Serialize(o, this);
        if (this.TypeResolver != null)
            string str = this.TypeResolver.ResolveTypeId(o.GetType());
            if (str != null)
                dictionary["__type"] = str;
        this.SerializeValueInternal(o, sb, depth, objectsInUse);

If the type can't be determined, serialization will still proceed, but the type will be ignored. The good news is that since anonymous types inherit getType() and the names returned are dynamically generated by the compiler, the TypeResolver returns null for ResolveTypeId and the "__type" attribute is subsequently ignored.

I also took John Morrison's advice with the internal constructor just in case, though using just this method, I was still getting __type properties in my JSON response.

//Given the following class
public class Foo
    internal Foo()


    public uint Bar

[WebService(Namespace = "")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class MyService : System.Web.Services.WebService

    //Return Anonymous Type to omit the __type property from JSON serialization
    [WebMethod(EnableSession = true)]
    [System.Web.Script.Services.ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)]
    public object GetFoo(int pageId)
        //Kludge, returning an anonymois type using link, prevents returning the _type attribute.
        List<Foo> foos = new List<Foo>();
        rtnFoos.Add( new Foo(){

        var rtn = from g in foos.AsEnumerable()
                   select g;

        return rtn;

Note: I'm using an inherited JSON type converter that reads the XML Serialization attributes from serialized types to further compress the JSON. With thanks to CodeJournal. Works like a charm.

@Groxx 2011-03-21 22:31:57

Why in the world would they think it was a good idea to modify your custom serialization after you finished making changes? I'm in ASP.NET 2.0, no var keyword here. Know if there's another way similar to this?

@sean 2009-06-03 08:32:00

Do not use the [Serializable] attribute.

The following should just do it

JavaScriptSerializer ser = new JavaScriptSerializer(); string json = ser.Serialize(objectClass);

@Alex Pandrea 2019-03-27 15:29:12

it outputs a JSON that has escaped quotas ( \" ) on all keys - which must be dealt with on client side. To avoid this (double JSON formatting) see . You also must use the System.Web.Script.Serialization namespace found in System.Web.Extensions.dll

Related Questions

Sponsored Content

53 Answered Questions

[SOLVED] Can comments be used in JSON?

  • 2008-10-28 20:39:03
  • Michael Gundlach
  • 2296055 View
  • 7594 Score
  • 53 Answer
  • Tags:   json comments

24 Answered Questions

[SOLVED] How do I POST JSON data with cURL?

36 Answered Questions

[SOLVED] What is the correct JSON content type?

41 Answered Questions

[SOLVED] How do I format a Microsoft JSON date?

55 Answered Questions

[SOLVED] How can I pretty-print JSON in a shell script?

27 Answered Questions

[SOLVED] Safely turning a JSON string into an object

  • 2008-09-05 00:12:01
  • Matt Sheppard
  • 1265374 View
  • 1334 Score
  • 27 Answer
  • Tags:   javascript json

7 Answered Questions

[SOLVED] Why does Google prepend while(1); to their JSON responses?

25 Answered Questions

[SOLVED] pretty-print JSON using JavaScript

27 Answered Questions

[SOLVED] JavaScriptSerializer - JSON serialization of enum as string

Sponsored Content