using dictionaries with WebServices
Posted
by umit-alba
on Stack Overflow
See other posts from Stack Overflow
or by umit-alba
Published on 2010-05-31T14:08:33Z
Indexed on
2010/05/31
14:13 UTC
Read the original article
Hit count: 260
Hi! I tried to pass a dictionary via WebServices. However it is not serializeable. So i wrote an Own Class that makes it serializeable:
using System;
using System.Net;
using System.Windows;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Xml;
using System.Xml.Schema;
namespace Platform
{
public class SaDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
{
#region Constructors
public SaDictionary()
: base()
{
}
public SaDictionary(IDictionary<TKey, TValue> dictionary)
: base(dictionary)
{
}
public SaDictionary(IEqualityComparer<TKey> comparer)
: base(comparer)
{
}
public SaDictionary(int capacity)
: base(capacity)
{
}
public SaDictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer)
: base(dictionary, comparer)
{
}
public SaDictionary(int capacity, IEqualityComparer<TKey> comparer)
: base(capacity, comparer)
{
}
//protected SaDictionary(SerializationInfo info, StreamingContext context)
// : base(info, context)
//{
//}
#endregion
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
bool wasEmpty = reader.IsEmptyElement;
reader.Read();
if (wasEmpty)
return;
while (reader.NodeType != XmlNodeType.EndElement)
{
reader.ReadStartElement("item");
reader.ReadStartElement("key");
TKey key = (TKey)keySerializer.Deserialize(reader);
reader.ReadEndElement(); //key
reader.ReadStartElement("value");
TValue value = (TValue)valueSerializer.Deserialize(reader);
reader.ReadEndElement(); //value
this.Add(key, value);
reader.ReadEndElement(); //item
// reader.MoveToContent();
}
reader.ReadEndElement();
}
public void WriteXml(XmlWriter writer)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
foreach (TKey key in this.Keys)
{
writer.WriteStartElement("item");
writer.WriteStartElement("key");
keySerializer.Serialize(writer, key);
writer.WriteEndElement(); //key
writer.WriteStartElement("value");
TValue value = this[key];
valueSerializer.Serialize(writer, value);
writer.WriteEndElement(); //value
writer.WriteEndElement(); //item
}
}
}
}
However i get an ArrayOfXElement back. Is there a way to cast it back to a Dictionary? greets
© Stack Overflow or respective owner