Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure JSON.NET to ignore DataContract/DataMember attributes

We are running into a situation on an MVC3 project with both the Microsoft JSON serializers and JSON.NET.

Everybody knows DateTime's are basically broken in Microsoft's serializers, so we switched to JSON.NET to avoid this issue. That works great, except that some of the classes we are trying to serialize are POCOs with DataContract/DataMember attributes. They are defined in an assembly that is referenced in multiple places. Additionally, they have some other display properties that are not marked as DataMembers for efficiency. For instance, a Customer

[DataContract] public class Customer {    [DataMember]    public string FirstName { get; set;}    [DataMember]    public string LastName { get; set;}    public string FullName     {        get        {  return FirstName + " " + LastName; }    }  } 

When this customer is passed over WCF the client side can reference that assembly and use the FullName just fine, but when serialized with JSON.NET it sees that FullName isn't a [DataMember] and doesn't serialize it. Is there an option to pass to JSON.NET to tell it to ignore the fact that a class has [DataContract] attribute applied?

Note: Using the JavaScriptSerializer in .NET works fine for the FullName property, but DateTimes are broken. I need JSON.NET to ignore the fact that this class has DataContract/DataMember attributes and just do standard public field serialization like it would if they weren't there.

like image 802
Nick Avatar asked Jun 15 '12 17:06

Nick


People also ask

Is DataMember attribute required?

You must specify [DataMember] attribute on the property or the field of your Data Contract class to identify it as a Data Member.

What is DataContract and DataMember?

A datacontract is a formal agreement between a client and service that abstractly describes the data to be exchanged. In WCF, the most common way of serialization is to make the type with the datacontract attribute and each member as datamember.

What is DataContract attribute?

[DataContract] attribute specifies the data, which is to serialize (in short conversion of structured data into some format like Binary, XML etc.) and deserialize(opposite of serialization) in order to exchange between the client and the Service.

Is DataContract mandatory in WCF?

No, the DataContractAttribute is not required - WCF will infer serialization rules.


1 Answers

Simply use Json.Net's OptOut attribute. It will take precedence over DataContract.

[DataContract] [JsonObject(MemberSerialization.OptOut)] 
like image 186
seldary Avatar answered Oct 25 '22 11:10

seldary