How do I implement XML serialization for custom types?

I have some types that I want to serialize / deserialize and create a UI based on the selected object. The UI will also modify the object, which in turn I will have to serialize in order to store it in my application.

So:

[obj_apple stored in the app] -> select obj_apple -> deserialize -> show in UI -> use the UI to change obj_apple -> deselect obj_apple -> serialize -> [obj_apple stored in the app]

      

Objects must be serialized / deserialized and this data must be string. This is why I thought having an xml serializer would be better.

What type of serializer would be the best? And are there any good examples for implementing this for custom types?

+2


source to share


2 answers


You have several options for strings; xml, which can be done simply with XmlSerializer

(or DataContractSerializer

, but this has much less control over xml) or JSON (JSON.net, etc.).

Typical classes for XmlSerializer

would simply look like this:

public class Apple {
    public string Variety {get;set;}
    public decimal Weight {get;set;}
    // etc
}

      

(note, I would expect the above to work for JSON.net too)

This class should also work great in data binding scenarios, etc. thanks to the properties.

You would serialize this:



    Apple obj = new Apple { Variety = "Cox", Weight = 12.1M};
    XmlSerializer ser = new XmlSerializer(typeof(Apple));

    StringWriter sw = new StringWriter();
    ser.Serialize(sw, obj);
    string xml = sw.ToString();

    StringReader sr = new StringReader(xml);
    Apple obj2 = (Apple)ser.Deserialize(sr);

      

but you can customize the xml:

[XmlType("apple"), XmlRoot("apple")]
public class Apple {
    [XmlAttribute("variety")]
    public string Variety {get;set;}
    [XmlAttribute("weight")]
    public decimal Weight {get;set;}
    // etc
}

      

DataContractSerializer

is ideal:

[DataContract]
public class Apple {
    [DataMember]
    public string Variety {get;set;}
    [DataMember]
    public decimal Weight {get;set;}
}

      

+1


source


DataContractSerializer all day.



+2


source







All Articles