Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize Dictionary<string, string> through WCF?

Tags:

I have a data contract with a data member typed as Dictionary<string, string>.

The generated web service reference exposes this as a member with the type ArrayOfKeyValueOfstringstringKeyValueOfstringstring[].

Has anyone seen this before?

like image 232
Hugh Avatar asked Oct 02 '09 15:10

Hugh


People also ask

Can you serialize a dictionary?

NET objects is made easy by using the various serializer classes that it provides. But serialization of a Dictionary object is not that easy. For this, you have to create a special Dictionary class which is able to serialize itself. The serialization technique might be different in different business cases.

What is serialization in WCF?

Windows Communication Foundation (WCF) uses the DataContractSerializer as its default serialization engine to convert data into XML and to convert XML back into data. The DataContractSerializer is designed to serialize data contract types.

What is serialization and Deserialization in WCF?

For an introduction to data contracts, see Using Data Contracts. When deserializing XML, the serializer uses the XmlReader and XmlWriter classes. It also supports the XmlDictionaryReader and XmlDictionaryWriter classes to enable it to produce optimized XML in some cases, such as when using the WCF binary XML format.


1 Answers

WCF only serializes structure, because what ends up on the wire must be self-contained enough to be useful for any client, not just .NET clients.

Some client developed on a different platform may not share the concept of a 'dictionary', so it would be too constraining to serialize a Dictionary to a representation that carries an implicit knowledge about the underlying class.

The client may not even be object-oriented.

A Dictionary is more than structure - it also contains behavior (e.g. when you assign to a key that already exists, you overwrite that key, etc.) and that behavior cannot travel across the wire.

In other words, Dictionaries and many other .NET types are not interoperable, so WCF will not attempt to preserve them in a ServiceContract.

You would probably be better off designing a custom DataContract for your data.

like image 126
Mark Seemann Avatar answered Oct 27 '22 22:10

Mark Seemann