How to deserialize a collection with children's collections?

I have a set of custom object objects, one of which is ArrayList

byte arrays.

The custom object is serialized and the collection property has the following attributes: [XmlArray("Images"), XmlArrayItem("Image",typeof(byte[]))]

So I serialize a collection of these custom entities and pass them to the web service as a string.

The web service receives a clock and a byte array,

The following code then tries to deserialize the collection - back to custom objects for processing ...

XmlSerializer ser = new XmlSerializer(typeof(List<myCustomEntity>));
StringReader reader = new StringReader(xmlStringPassedToWS);
List<myCustomEntity> entities = (List<myCustomEntity>)ser.Deserialize(reader);

foreach (myCustomEntity e in entities)
{
    // ...do some stuff...

    foreach (myChildCollection c in entities.ChildCollection
    {
        // .. do some more stuff....
    }
}

      

I checked the XML I got from the initial serialization and it contains a byte array - a child collection just like the StringReader built above.

After the deserialization process, the resulting set of custom entites is fine, except that each object in the collection contains no items in its child collection. (ie doesn't get to "... do a few more things ..." above.

Can someone please explain what I am doing wrong? Is it possible to serialize ArrayLists in a shared collection of custom objects?

+1


source to share


2 answers


Properties of serializable classes that are to be serialized must be read / written.

In my case, the above is a read-only ArrayList property. It returned byte arrays based on a separate function to which filenames were appended.



Once the setter has been written for the ArrayList property, and the logic has changed slightly throughout the Add method, the serialization works.

Lesson: for serializable classes that need to be reconstructed from a serialized stream, all serialized properties must be writable - something obvious when you say this.

0


source


There are many options depending on what you are doing ... Explore the Xml attributes in the System.Xml.Serialization namespace ... In particular, check

[XmlArrayItem (ElementName = "")]



This refers to a property of a class that is typed as some set (I think it needs to implement an IList) and will be populated by the XmlDeserializer with Xml elements named "ElementName" ...

This namespace has a whole bunch of Xml attributes that can be used to fine-tune serialization and deserialization. You can create almost any class structure you want, styling appropriately with the correct Xml * Atttributes

+2


source







All Articles