hokapoka
hokapoka

Reputation: 479

C# XML & JSON serialization of a class include / exclude properties differently in each format

I'm am trying to serialize a class into both XML & JSON.

This is rather trivial, however I need to exclude some properties that are included in the XML output from the output of the JSON.

For example :

[DataContract]
public class Foobar
{
    [DataMember]
    [XmlElement("somestr")]
    public string SomeString

    [XmlElement("otherstr")]
    public string OtherString

}

Now normally, when not using [XmlElement("tag_name")], simply omitting [DataContract] on a property is sufficient to exclude "OtherString" it when serialized to JSON.

My tests appear to show that the [XmlElement] directive is telling the JSON serializer to include them.

Has anyone got any suggestions on how I can go about controling the output so that it's different for JSON & XML?

Many thanks.

Upvotes: 1

Views: 1410

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062610

You could try adding [IgnoreDataMember] to OtherString. However you may find it easier just to split into 2 DTO classes - 1 for json, one for DCS. If you use JavaScriptSerializer, a twinned JavaScriptConverter is pretty easy to write, so that is another viable option (you might even be able to get away with just [ScriptIgnore]).

Upvotes: 1

Related Questions