Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Uri implements ISerializable, but gives error? [duplicate]

Possible Duplicate:
How to (xml) serialize a uri

To my knowledge Uri implements ISerializable, but throws error when used like this:

XmlSerializer xs = new XmlSerializer(typeof(Server));
xs.Serialize(Console.Out, new Server { Name = "test", URI = new Uri("http://localhost/") });

public class Server
{
    public string Name { get; set; }
    public Uri URI { get; set; }
}

Works just fine if Uri type is changed to string.

Anyone knows what is the culprit?


Solution proposed by Anton Gogolev:

public class Server
{
    public string Name { get; set; }

    [XmlIgnore()]
    public Uri Uri; 
    
    [XmlElement("URI")]
    public string _URI // Unfortunately this has to be public to be xml serialized.
    { 
        get { return Uri.ToString(); }
        set { Uri = new Uri(value); }
    }
}

(Thanks for SLaks also pointing out the backwardness of my method...)

This produces XML output:

<Server>
    <URI>http://localhost/</URI>
    <Name>test</Name>
</Server>

I rewrote it here so the code is visible.

like image 490
Ciantic Avatar asked Oct 20 '09 11:10

Ciantic


2 Answers

In order to be serialized to XML, Uri class should have a parameterless constructor, which it doesn't: Uri is designed to be immutable. Honestly, I can't see why it cannot be serialized without having a parameterless constructor.

To circumvent this, either change URI property type to string, or add one more property called _URI, mark URI with XmlIgnoreAttribute and rewrite it's get method as get { return new Uri(_URI); }.

like image 118
Anton Gogolev Avatar answered Nov 15 '22 19:11

Anton Gogolev


You're confusing binary serialization with XML serialization.

XML serialization is a very simple process that saves field values and restores into a new object.

Binary serialization is much more powerful, and allows the object to control serialization behavior. The ISerializable interface, which Uri does implement, is only used for binary serialization.

like image 40
SLaks Avatar answered Nov 15 '22 21:11

SLaks