小编典典

使ASP.NET WCF将字典转换为JSON,省略“键”和“值”标签

c#

这是我的困境。我使用的是RESTful ASP.NET服务,试图获取一个函数以以下格式返回JSON字符串:

{"Test1Key":"Test1Value","Test2Key":"Test2Value","Test3Key":"Test3Value"}

但是我却以这种格式获取它:

[{"Key":"Test1Key","Value":"Test1Value"},
{"Key":"Test2Key","Value":"Test2Value"},
{"Key":"Test3Key","Value":"Test3Value"}]

我的方法如下所示:

[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public Dictionary<string, string> Test(String Token)
{
    if (!IsAuthorized(Token))
        return null;

    if (!IsSecure(HttpContext.Current))
        return null;

    Dictionary<string, string> testresults = new Dictionary<string, string>();
    testresults.Add("Test1Key", "Test1Value");
    testresults.Add("Test2Key", "Test2Value");
    testresults.Add("Test3Key", "Test3Value");
    return testresults;
}

有什么方法可以仅使用内置的ASP.NET工具摆脱那些“键”和“值”标签?(即,如果可以避免,我宁愿不使用JSON.NET)

非常感谢!:)


阅读 277

收藏
2020-05-19

共1个答案

小编典典

.NET字典类除了您描述的方法之外,不会序列化任何其他方法。但是,如果您创建自己的类并包装字典类,则可以覆盖序列化/反序列化方法,并能够执行所需的操作。请参见下面的示例,并注意“
GetObjectData”方法。

    [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] );
        }
    }
2020-05-19