开发者

XmlSerializer - Error serializing an object with a URI property

开发者 https://www.devze.com 2023-01-23 02:09 出处:网络
I\'m having trouble serializing a class with a Uri property. System.InvalidOper开发者_JS百科ationException was unhandled

I'm having trouble serializing a class with a Uri property.

System.InvalidOper开发者_JS百科ationException was unhandled
  Message=There was an error reflecting type 'Foo.Story'.
  // ...
  InnerException: System.InvalidOperationException
       Message=There was an error reflecting property 'MyURI'.

I would like this property to be serialized. What is a way around this? Should I declare some sort of a converter, and use the string representation of the URI?


The Uri class is not serializable to XML, because all it doesn't have a default constructor and all its properties are read-only. As a workaround, you can serialize a string instead:

[XmlIgnore]
public Uri MyURI { get; set; }

[XmlElement("MyURI")]
public string MyURIAsString
{
    get { return MyURI != null ? MyURI.AbsoluteUri : null; }
    set { MyUri = value != null ? new Uri(value) : null; }
}


Does it have to be XmlSerializer ? DataContractSerializer would work:

    using (var stream = File.Create(@"c:\Uri.xml"))
        new DataContractSerializer(typeof(Uri)).WriteObject(stream, new Uri(@"http://www.contoso.com/"));

Here is a nice article that sums up the differences

0

精彩评论

暂无评论...
验证码 换一张
取 消