Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLSerializer doesn't serialize class properties and returns only bool - 'false' values for *Specified members

Having class code autogenerated by WCF/svcutil.exe like that:

public class Foo
{

    private float barField;

    bool barFieldSpecified;

    public float bar
    {
        get
        {
            return this.barField;
        }
        set
        {
            this.barField = value;
        }
    }

    [System.Xml.Serialization.SoapIgnore]
    public bool barSpecified
    {
        get
        {
            return this.barFieldSpecified;
        }
        set
        {
            this.barFieldSpecified = value;
        }
    }        
} 

and using XMLSerializer like that:

        Foo foo = new Foo();
        foo.bar = 100;
        var ser = new XmlSerializer(typeof(Foo));
        var ms = new MemoryStream();
        ser.Serialize(ms, foo);
        var str = Encoding.UTF8.GetString(ms.ToArray()); 

I get XML with values in all nodes set to 'false' and none of my class properties I set.

like image 915
user1121956 Avatar asked Oct 22 '25 21:10

user1121956


1 Answers

The reason of such behaviour is that XMLSerializer make usage of these additional properties ending with 'Specified' keyword for value-typed properties like bar and barSpecified in code above. If barSpecified is not set to 'true', bar property will not be serialized. It's XMLSerializer's way of saying that bar is kind of NULL and shouldn't be serialized.

There are at least 3 possibilities for solving that:

-removing barSpecified property and field

-setting barSpecified to 'true'

-if class implements INotifyPropertyChanged make usage of it (if class is autogenerated it's good to make it as partial class in another file like below):

   public partial class Foo
   {
        public Foo()
        {
            this.PropertyChanged += (object sender, System.ComponentModel.PropertyChangedEventArgs e) =>
                {
                    if (!e.PropertyName.EndsWith("Specified"))
                    {
                        var prop = this.GetType().GetProperty(e.PropertyName + "Specified");
                        if (prop != null)
                            prop.SetValue(this, true, null);
                    }
                };
        }
    }
like image 189
user1121956 Avatar answered Oct 25 '25 10:10

user1121956