Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore properties of class when using WCF ResponseFormat = WebMessageFormat.Json

Tags:

json

c#

wcf

I'm using WCF for JSON services using this format:

[OperationContract]
[ServiceKnownType(typeof(ComplexResult))]
[WebInvoke(
            Method = "GET",
            BodyStyle = WebMessageBodyStyle.Bare,
            ResponseFormat = WebMessageFormat.Json)]
MyClass MyFunction(string myParams);

This works great, however it has a limitation. I can't ignore properties of my class that I'm serializing to JSON. If I use the JavaScriptSerializer class then I can put [ScriptIgnore] attributes on the properties I want to ignore and they won't be serialized in the JSON, however this does not work with the method above.

Is there a way to exclude properties of the classes getting serialized to JSON using the ResponseFormat Json method?

like image 878
Justin Avatar asked Dec 22 '22 07:12

Justin


1 Answers

WCF by default uses the DataContractJsonSerializer to serialize objects. Depending on how MyClass is defined, you can use different attributes to prevent members from being serialized:

  • If MyClass doesn't have any attribute (i.e., it's a "POCO" type), you can use the [IgnoreDataMember] attribute in the members you don't want serialized
  • If MyClass is decorated with [Serializable], you can use the [NotSerialized] attribute in those members
  • If MyClass is decorated with [DataContract], then you just need to not add [DataMember] to the members you don't want serialized.
like image 190
carlosfigueira Avatar answered Jan 24 '23 19:01

carlosfigueira