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

后端 未结 5 1624
别跟我提以往
别跟我提以往 2020-11-27 05:58

Here\'s my dilemma. I\'m using a RESTful ASP.NET service, trying to get a function to return a JSON string in this format:

{\"Test1Key\":\"Test1Value\",\"Te         


        
5条回答
  •  时光取名叫无心
    2020-11-27 06:47

    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 : ISerializable
        {
            private Dictionary _Dictionary;
            public AjaxDictionary()
            {
                _Dictionary = new Dictionary();
            }
            public AjaxDictionary( SerializationInfo info, StreamingContext context )
            {
                _Dictionary = new Dictionary();
            }
            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] );
            }
        }
    

提交回复
热议问题