Make ASP.NET WCF convert dictionary to JSON, omitting "Key" & "Value" tags Make ASP.NET WCF convert dictionary to JSON, omitting "Key" & "Value" tags asp.net asp.net

Make ASP.NET WCF convert dictionary to JSON, omitting "Key" & "Value" tags


The .NET dictionary class won't serialize any other way than the way you described. But if you create your own class and wrap the dictionary class then you can override the serializing/deserializing methods and be able to do what you want. See example below and pay attention to the "GetObjectData" method.

    [Serializable]    public class AjaxDictionary<TKey, TValue> : ISerializable    {        private Dictionary<TKey, TValue> _Dictionary;        public AjaxDictionary()        {            _Dictionary = new Dictionary<TKey, TValue>();        }        public AjaxDictionary( SerializationInfo info, StreamingContext context )        {            _Dictionary = new Dictionary<TKey, TValue>();        }        public TValue this[TKey key]        {            get { return _Dictionary[key]; }            set { _Dictionary[key] = value; }        }        public void Add(TKey key, TValue value)        {            _Dictionary.Add(key, value);        }        public void GetObjectData( SerializationInfo info, StreamingContext context )        {            foreach( TKey key in _Dictionary.Keys )                info.AddValue( key.ToString(), _Dictionary[key] );        }    }


Expanding slightly on @MarkisT's excellent solution, you can modify the serialization constructor to recreate one of these dictionaries from the same JSON (thus allowing you to take an AjaxDictionary as a service parameter), as follows:

public AjaxDictionary( SerializationInfo info, StreamingContext context ){     _Dictionary = new Dictionary<TKey, TValue>();     foreach (SerializationEntry kvp in info)     {         _Dictionary.Add((TKey)Convert.ChangeType(kvp.Name, typeof(TKey)), (TValue)Convert.ChangeType(kvp.Value, typeof(TValue)));     }}


In case anyone has that problem on the client side: conversion from that weird {Key: "x", Value:"y"} Array to a { x: "y" } object can be done in a single line of JS:

var o = i.reduce(function (p, c, a, i) { p[c.Key] = c.Value; return p }, {});

with i being the array returned from the service, and o being what you actually want.

best regards