views:

282

answers:

2

I have some types that I want to serialize/deserialize and generate a UI based on the selected object. The UI will also change the object which in turn I will have to serialize to store it in my app.

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]

The objects have to be serialized/deserialized and this data has to be string. That's why I thought having an xml serializer would be better.

Which type of serializer would be the best? And are there any good examples to implement this for custom types?

+2  A: 

DataContractSerializer all day.

Gurdas Nijor
This is the correct answer, but you should elaborate.
John Saunders
+1  A: 

You have a few choices for strings; xml, which can be done simply with XmlSerializer (or DataContractSerializer, but that offers much less control over the xml) or JSON (JSON.net, etc).

Typical classes for XmlSerializer would look simply like:

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

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

The above class should also work fine 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 ideally more like:

[DataContract]
public class Apple {
    [DataMember]
    public string Variety {get;set;}
    [DataMember]
    public decimal Weight {get;set;}
}
Marc Gravell
Thanks Marc, very cool examples.
Joan Venge
Btw Marc, can I use XmlSerializer ser = new XmlSerializer(typeof(obj.GetType()));I am just wondering if typeof has an advantage in this case?
Joan Venge
new XmlSerializer(obj.GetType());
Marc Gravell
Thanks Marc. I typed it wrong :)
Joan Venge