使ASP.NET WCF将字典转换为JSON,省略"Key"和"Value"标记

Kat*_*ams 30 c# asp.net rest wcf json

这是我的困境.我正在使用RESTful ASP.NET服务,尝试使用以下格式返回JSON字符串的函数:

{"Test1Key":"Test1Value","Test2Key":"Test2Value","Test3Key":"Test3Value"}
Run Code Online (Sandbox Code Playgroud)

但我会以这种格式得到它:

[{"Key":"Test1Key","Value":"Test1Value"},
{"Key":"Test2Key","Value":"Test2Value"},
{"Key":"Test3Key","Value":"Test3Value"}]
Run Code Online (Sandbox Code Playgroud)

我的方法看起来像这样:

[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;
}
Run Code Online (Sandbox Code Playgroud)

有没有办法只使用内置的ASP.NET工具摆脱那些"Key"和"Value"标签?(即,如果可以避免的话,我宁愿不使用JSON.NET)

非常感谢!:)

小智 44

.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] );
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • 不知何故,这个例子对我不起作用.执行GET将导致"无响应",但我看到调试器调用了GetObjectData. (3认同)
  • 不幸的是,我不能给你一个upvote,因为我没有足够的声誉 - 我会将此标记为最佳答案,因为它最接近我的需要(我只是无法摆脱__type事情). (2认同)

Dan*_*son 5

稍微扩展 @MarkisT 的优秀解决方案,您可以修改序列化构造函数以从相同的 JSON 重新创建这些字典之一(从而允许您将 AjaxDictionary 作为服务参数),如下所示:

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)));
     }
}
Run Code Online (Sandbox Code Playgroud)