使 ASP.NET WCF 将字典转换为 JSON,省略“Key";&“价值"标签 [英] Make ASP.NET WCF convert dictionary to JSON, omitting "Key" & "Value" tags

查看:15
本文介绍了使 ASP.NET WCF 将字典转换为 JSON,省略“Key";&“价值"标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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","Test2Key":"Test2Value","Test3Key":"Test3Value"}

但我以这种格式获取它:

But I'm getting it in this format instead:

[{"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)

Is there any way I can get rid of those "Key" and "Value" tags using only built in ASP.NET tools? (i.e., I'd rather not use JSON.NET, if it's avoidable)

非常感谢!:)

推荐答案

.NET 字典类不会以您描述的方式以外的任何其他方式进行序列化.但是,如果您创建自己的类并包装字典类,那么您可以覆盖序列化/反序列化方法并能够执行您想要的操作.看下面的例子,注意GetObjectData"方法.

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] );
        }
    }

这篇关于使 ASP.NET WCF 将字典转换为 JSON,省略“Key";&amp;“价值"标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆