Reputation:
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?
Upvotes: 69
Views: 38973
Reputation: 1
This worked for me (.NET Framework 4.8.1) VS 2022 C# The JSON or any serializer object need to be generated with not to include typeinformation settings. Below is an example:
var settings = new DataContractJsonSerializerSettings();
settings.EmitTypeInformation = EmitTypeInformation.Never;
var serializer = new DataContractJsonSerializer(yourType, settings);
or
var serializer = new DataContractJsonSerializer(yourType, new DataContractJsonSerializerSettings() {EmitTypeInformation=EmitTypeInformation.Never});
Thanks to: Daniel https://stackoverflow.com/users/572644/daniel-hilgarth in
How do I tell DataContractJsonSerializer to not include the "__type" property
Upvotes: 0
Reputation: 1
The following does not remove __type attribute but replace content instead.
public class MyClass
{
//... your code
//... set __type to your own
public string __type => "blaah"; // results in: '__type: "blaah"'
}
Upvotes: 0
Reputation: 1
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.
Upvotes: 0
Reputation: 11
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());
Upvotes: 0
Reputation: 1158
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.
Upvotes: 0
Reputation:
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() { }
Upvotes: 40
Reputation: 1376
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);
}
Upvotes: 1
Reputation: 21548
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)
Upvotes: 25
Reputation: 1867
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
...
}
Upvotes: 4
Reputation: 21
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>
Upvotes: 2
Reputation: 4994
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:
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.
Upvotes: 5
Reputation: 48474
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;
Upvotes: 12
Reputation: 36
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.
Upvotes: 1
Reputation: 2122
Pass in null for the JavaScriptTypeResolver and the __type will not be serialized
JavaScriptSerializer serializer = new JavaScriptSerializer(null);
string json = serializer.Serialize(foo);
Upvotes: 3
Reputation: 2799
I not sure this a good solution , but if you use the Json.net library, you can ignore some properties by adding [JsonIgnore] attribute.
Upvotes: 2
Reputation: 3752
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="")]
Upvotes: -7
Reputation: 9659
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.
Upvotes: 16
Reputation: 5587
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.
Upvotes: 0
Reputation: 11624
Do not use the [Serializable] attribute.
The following should just do it
JavaScriptSerializer ser = new JavaScriptSerializer(); string json = ser.Serialize(objectClass);
Upvotes: 1