【发布时间】:2016-11-08 00:44:04
【问题描述】:
所以我有一个服务合同,我像 API 一样使用具有以下接口声明的服务合同
namespace MyAPI
{
[ServiceContract(Namespace = "http://MyAPI")]
public interface IMyAPI
{
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "GetSomething?someInt={someInt}", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
Dictionary<string, List<string>> GetSomething(int someInt);
}
}
在实现中我做了如下的事情
namespace MyAPI
{
[ServiceBehavior]
public class MyAPI : IMyAPI
{
public Dictionary<string, List<string>> GetSomething(int someInt)
{
Dictionary<string, List<string>> something = new Dictionary<string, List<string>>();
something["FIRST KEY"] = new List<string>();
something["SECOND KEY"] = new List<string>();
// fill up these lists...
return something;
}
}
}
但是,当我去返回一些东西时,我得到的东西是这样格式化的
[{"Key":"FIRST KEY","Value":[]},{"Key":"SECOND KEY","Value":[]}]
我希望 JSON 如下所示
{"FIRST KEY":[], "SECOND KEY":[]}
为什么两者之间有区别?我可以序列化成一个字符串,但这似乎是一个额外的(不必要的)步骤。非常感谢任何帮助
【问题讨论】:
-
无论好坏,
System.Collections.Generic.Dictionary<TKey,TValue>序列化为System.Collections.Generic.KeyValuePair<TKey,TValue>的数组。这就是“为什么”;我正在四处寻找解决办法。 -
使用 Json.NET 会给你想要的输出。
-
我认为这可能是主题? stackoverflow.com/a/10368876/424129
-
您必须先序列化此字典并返回 json ..然后在客户端接收 json 并再次将其反序列化为字典。