简体   繁体   中英

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.

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] ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM