2016-11-07 50 views
0

所以,我有我喜欢使用的API有以下接口声明JSON回报C#的ServiceContract看起来不同于我期望

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":[]} 

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

+0

是好是坏,'System.Collections.Generic.Dictionary '序列化为System.Collections.Generic.KeyValuePair 的'阵列'。这就是“为什么”;我正在四处寻找解决办法。 –

+0

使用Json.NET将为您提供所需的输出。 – rinukkusu

+0

我认为这可能是主题? http://stackoverflow.com/a/10368876/424129 –

回答

1

这是因为“东西”是一个容器 - >一个键值对的列表。 这就是为什么你得到的结构["key<string>": value<Array<string>>] 对不起,这只是我的记谱。

所以一个字典转换为一个数组,因为它是一个集合。其结构是保存碰巧是参考类型的关键值对。这就是为什么你在JSON中获得对象表示法的原因。该值再次是字符串列表,这就是数组语法的原因。

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

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

    [DisplayName("SECOND KEY")] 
    List<string> SecondKey; 
} 
相关问题