What's the best way to serialize a HashTable (or a data best navigated through a string indexer) with SOAP/XML?
Let's say I have a Foo
that has an property Bar[] Bars
. A Bar
object has a key and a value. By default, this serializes to the following XML:
<Foo>
<Bars>
<Bar key="key0" value="value0"/>
...
</Bars>
</Foo>
For JSON, this serializes to:
{"Foo":["Bars":[{"Key":"key0","Value":"key1} ... ]}]}
What I'd really like to have is this serialize to better reflect the underlying relationship. E.g.,
<Foo>
<Bars>
<Key0 value="value0"/>
<Key1 value="value1"/>
...
</Bars>
</Foo>
I realize there are some challenges with serializing to SOAP in this way, but what's the best approach to providing a schema that better reflects this?
I've tried creating a BarsCollection object and defining custom serialization on that, but it doesn't seem to actually invoke the serialization on that object. E.g.
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
foreach (Bar bar in Bars){
info.AddValue(bar.Key. bar);
}
}
Any suggestions? What's the best practice here?
Best Answer
I really don't think that what you want reflects the structure better. To define a schema (think XSD) for this you would have to know all of the potential keys in advance since you indicate that you want each one to be a separate custom type. Conceptually Bars would be an array of objects holding objects of type Key0, Key1, with each of the KeyN class containing a value property. I believe that the first serialization actually is the best reflection of the underlying structure. The reason it "works" more like you want in JSON is that you lose the typing -- everything is just an object. If you don't care about the types why not just use JSON?