How to not serialize the __type property on JSON objects
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() { }
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:
[WebMethod]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.
[WebMethod]public static object ApplyCredits(int addonid, int[] vehicleIds)
instead of
[WebMethod]public static WebMethodReturn ApplyCredits(int addonid, int[] vehicleIds)
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 /> </behavior>
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.