C#ServiceContract的JSON返回看起来与我预期的不同

时间:2016-11-07 16:27:54

标签: c# json

所以我有一个服务合同,我正在使用API​​作为具有以下接口声明的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":[]}

为什么两者有区别?我可以序列化成一个字符串,但这似乎是一个额外的(不必要的)步骤。非常感谢任何帮助

1 个答案:

答案 0 :(得分:1)

这是因为&#34;某事&#34;是一个容器 - &gt;键值对列表。 这就是为什么你得到["key<string>": value<Array<string>>]的结构 对不起,这只是我的记号。

因此,字典会转换为数组,因为它是集合。它的结构是保存恰好是引用类型的键值对。这就是你在JSON中获得对象表示法的原因。该值是一个字符串列表,这就是数组语法。

您的预期结构描述了一个具有2个属性的对象,如:

class SomeThing{
    [DisplayName("FIRST KEY")]
    List<string> FirstKey;

    [DisplayName("SECOND KEY")]
    List<string> SecondKey;
}