Note that there are some explanatory texts on larger screens.

plurals
  1. POIgnore a property during xml serialization but not during deserialization
    text
    copied!<p>In C#, how can I make XmlSerializer ignore a property during serialization but not during deserialization? (Or how do I do the same with Json.net?)</p> <p>To prevent a property from being serialized, you can add the <code>XmlIgnore</code> attribute:</p> <pre><code>[XmlIgnore] public int FooBar {get;set;} </code></pre> <p>This will cause the <code>&lt;FooBar&gt;</code> tag to be omitted during serialization.</p> <p>However, this also means that the <code>&lt;FooBar&gt;</code> tag will be ignored during deserialization.</p> <p>In my case, I accept an array of items from user in the request, and for each item user can specify an action property if they want to add, modify or delete the item. I want to use the same model object for GET list calls, and don't want to return this action property. I expect this would be a pretty common case.</p> <p>Another use case: say you have a circle object</p> <pre><code>public class Circle { public double Radius { get; set; } } </code></pre> <p>and you modify it to add a diameter property</p> <pre><code>public class Circle2 { public double Diameter { get; set; } public double Radius { get { return Diameter / 2; } set { Diameter = value*2; } } } </code></pre> <p>You may want to serialize only the diameter, but still be able to deserialize xml files in the old format that contain only the radius.</p> <p>I did my research and didn't find anything, hence this question</p> <p><strong>Solution</strong>: I figured out the solution. I can add a ShouldSerialize property which always return false, details at <a href="https://docs.microsoft.com/en-us/dotnet/framework/winforms/controls/defining-default-values-with-the-shouldserialize-and-reset-methods" rel="nofollow noreferrer">this MSDN documentation</a></p> <p><em>(this solution could be added as an actual answer if this question is reopened)</em></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload