How to not serialize the __type property on JSON objects

C#asp.netJsonAsmxJavascriptserializer

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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() { }

Solution 2 - C#

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)

Solution 3 - C#

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.

Solution 4 - C#

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;

Solution 5 - C#

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 = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
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; }
    }

    [WebMethod]
    public String MyMethodA(Cat cat)
    {
        return "return value does not matter";
    }

    [WebMethod]
    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.

Solution 6 - C#

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

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

Solution 7 - C#

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:

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

Solution 8 - C#

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

Solution 9 - C#

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.:

<endpointBehaviors>
  <behavior name="MyServiceEndpoint">
    <webHttp/>
  </behavior>
</endpointBehaviors>

Solution 10 - C#

Do not use the [Serializable] attribute.

The following should just do it

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

Solution 11 - C#

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.

Before.

[DataMember]
public List<Person> People { get; set; }

After.

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.

Solution 12 - C#

Here is a way around that

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

        HttpContext.Current.Response.Write(json);
    }

Solution 13 - C#

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;
            }
        }
        sb.Append(this.Serialize(dictionary));
    }
    else
    {
        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
[XmlType("T")]
public class Foo
{
    internal Foo()
    {

    }

    [XmlAttribute("p")]
    public uint Bar
    {
        get;
        set;
    }
}

[WebService(Namespace = "http://me.com/10/8")]
[System.ComponentModel.ToolboxItem(false)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
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(){
            Bar=99
        }};

        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.

Solution 14 - C#

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,
                  SubTotal=response.SubTotal};
    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.

Solution 15 - C#

You can use create your own return type for sending response. and also while sending response use object as return type .so _type property will be get ignored.

Solution 16 - C#

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());

Solution 17 - C#

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="")]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRobertView Question on Stackoverflow
Solution 1 - C#John MorrisonView Answer on Stackoverflow
Solution 2 - C#Stephen KennedyView Answer on Stackoverflow
Solution 3 - C#Jonathan SayceView Answer on Stackoverflow
Solution 4 - C#Brett VeenstraView Answer on Stackoverflow
Solution 5 - C#ClearCloud8View Answer on Stackoverflow
Solution 6 - C#AdamView Answer on Stackoverflow
Solution 7 - C#EthermanView Answer on Stackoverflow
Solution 8 - C#MironlineView Answer on Stackoverflow
Solution 9 - C#Art KgView Answer on Stackoverflow
Solution 10 - C#seanView Answer on Stackoverflow
Solution 11 - C#MichaelView Answer on Stackoverflow
Solution 12 - C#Liran BarnivView Answer on Stackoverflow
Solution 13 - C#LaramieView Answer on Stackoverflow
Solution 14 - C#Alex PandreaView Answer on Stackoverflow
Solution 15 - C#mestriprasad01View Answer on Stackoverflow
Solution 16 - C#Muthupandi ThiruvadiView Answer on Stackoverflow
Solution 17 - C#dlchambersView Answer on Stackoverflow