How to serialize Dictionary<string, string> through WCF?
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.
As WCF has to convert everything to XML, it has to fit as XML... Collections are generally converted to arrays.
A Dictionary is prety hard to represent as xml, that's why you have this type on the other side. You can specify SvcUtil.exe to use specific collections instead of arrays in the generated proxy code, but I'm not sure it will work for a Dictionary. I would say that you should avoid using a Dictionary here, and use a simpler Collection.
What I would do is create my own data type, [DataContract] it, make it have two fields of type String, then make a Collection of these that you fill with everthing you find in the Dictionary. Then sent that Collection trough the wire, then convert it back to a Dictionary on the other side.
There is a way to do it.. The operation contract is actually a string. I escape the json string to keep it a string. I then in the web method unescape the string and parse it into a dictionary using NewtonSoftJson I used Dictionary but you could also do Dictionary if you wanted. Hope this is useful...
I used NewtonSoft Json library...
c# code
using Newtonsoft.Json;
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json)]
public void testMethod(string jsonData)
{
string data = Uri.UnescapeDataString(jsonData);
Dictionary<string, string> x = jsonConvert.DeserializeObject<Dictionary<string, string>>(data);
foreach (KeyValuePair<string, string> kvp in x)
{
}
}
JSCode
var Data = {
width: 400,
height: 200,
someString: "somedata"
};
$.ajax({
type: "POST",
url: "Service1.svc/testMethod",
contentType: "application/json; charset=utf-8",
dataType: "json",
timeout: 1000000,
data: '{"jsonData": "' + escape(JSON.stringify(Data)) + '"}',
error: function(error) {
},
success: function (data) {
},
});