Ignore a property during xml serialization but not during deserialization

后端 未结 2 1578
花落未央
花落未央 2020-12-01 03:17

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?)

To prevent a prop

相关标签:
2条回答
  • 2020-12-01 03:45

    This is the solution outlined by Manoj:

    If you want to suppress serialization of a specific property Foo, but still be able to deserialize it, you can add a method public bool ShouldSerializeFoo() that always returns false.

    Example:

    public class Circle2
    {
        public double Diameter { get; set; }
        public double Radius { get { return Diameter / 2; } set { Diameter = value*2; } }
    
        [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
        public bool ShouldSerializeRadius() {return false;}
    }
    

    This will cause the Radius to not be serialized, but still allow it to be deserialized.

    This method has to be public for the XMLSerializer to find it, so in order to avoid polluting the namespace you can add the EditorBrowsable attribute to hide it from the IDE. Unfortunately this hiding only works if the assembly is referenced as a DLL in your current project, but not if you edit the actual project with this code.

    0 讨论(0)
  • 2020-12-01 04:06

    If you want to ignore the element at serialization with XmlSerializer, you can use XmlAttributeOverrides:

    XmlAttributeOverrides overrides = new XmlAttributeOverrides();
    XmlAttributes attribs = new XmlAttributes();
    attribs.XmlIgnore = true;
    attribs.XmlElements.Add(new XmlElementAttribute("YourElementName"));
    overrides.Add(typeof(YourClass), "YourElementName", attribs);
    
    XmlSerializer ser = new XmlSerializer(typeof(YourClass), overrides);
    ser.Serialize(...
    
    0 讨论(0)
提交回复
热议问题