Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize a classes that included at System.Net.IPAddress property?

Tags:

c#

I want to serialize my class having property IPAddress.

public class Person
{
    public IPAddress MasterIP { get; set; }
    public Person(){}
}


public void SerializeMyClass()
{
    Person obj=new Person();
    XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());
    xmlSerializer.Serialize(obj);
}

But I am getting error:

"can not serialize IPaddress because it has no empty constructor"

like image 316
Sam Avatar asked Jun 10 '14 11:06

Sam


1 Answers

You can't - XmlSerializer can only serialize public properties/fields of public classes that have public parameterless constructors. You can either look into other serializer type (like BinaryFormatter) or hack your class like:

public class Person {
  [XmlIgnore]
  public IPAddress MasterIP { get; set; }
  [XmlElement("MasterIP")]
  public string MasterIPForXml {
    get { return MasterIP.ToString(); }
    set { MasterIP = string.IsNullOrEmpty(value) ? null :
      IPAddress.Parse(value); 
    }
  }
}
like image 120
Ondrej Svejdar Avatar answered Oct 05 '22 07:10

Ondrej Svejdar