这是我的两难境地.我正在使用一个REST风格的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工具就可以go 掉那些"key"和"value"标记呢?(即,如果可以避免,我宁愿不使用JSON.NET)

非常感谢!:)

推荐答案

NET DICTIONARY类不会以您所描述的方式以外的任何其他方式进行序列化.但是,如果您创建自己的类并包装DICTIONARY类,那么您可以覆盖序列化/反序列化方法,并能够执行您想要的操作.参见下面的示例,并注意"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] );
        }
    }

Asp.net相关问答推荐

Visual Studio发布的网站得到错误类型JObject is not defined when page is load on server"''"

Web 部署工具 2.1 和 Web 部署 3.5 有什么区别?从 VS 2010 部署需要哪一个?

我可以在一个 Web 项目中有多个 web.config 文件吗?

VS2013发布Web部署任务失败文件正在使用中

WebAPI 请求流支持

ASP.NET Membership:如何将用户设置为已登录

如何使用 json 将复杂类型传递给 ASP.NET MVC 控制器

有没有办法在外部 javascript 文件中使用<%= someObject.ClientID %>?

ASP.NET Web 应用程序消息框

.Net Standard 2.0 类库是否有通用配置文件?

错误:无法在 Web 服务器上开始调试... ASP.NET 4.0

将查询参数绑定到 ASP.NET Core 中的模型

如何进入 IIS 管理器?

主机与 DnsSafeHost

解析器错误:此处不允许使用_Default,因为它没有扩展类System.Web.UI.Page和 MasterType 声明

在 ASP.NET MVC 中获取服务器机器名称?

ASP.net 判断页面是 http 还是 https

获取 POST 变量

IE9 JavaScript 错误:SCRIPT5007:无法获取属性ui的值:对象为空或未定义

使用 FormsAuthentication.SetAuthCookie 存储更多信息