这是我的困境。我正在使用一个 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)
非常感谢! :)
最佳答案
.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] );
}
}
关于c# - 使 ASP.NET WCF 将字典转换为 JSON,省略 "Key"和 "Value"标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7590088/