【问题标题】:JSON return for C# ServiceContract looks different than I'd expectC# ServiceContract 的 JSON 返回看起来与我预期的不同
【发布时间】: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&lt;TKey,TValue&gt; 序列化为System.Collections.Generic.KeyValuePair&lt;TKey,TValue&gt; 的数组。这就是“为什么”;我正在四处寻找解决办法。
  • 使用 Json.NET 会给你想要的输出。
  • 我认为这可能是主题? stackoverflow.com/a/10368876/424129
  • 您必须先序列化此字典并返回 json ..然后在客户端接收 json 并再次将其反序列化为字典。

标签: c# json


【解决方案1】:

这是因为“某物”是一个容器 --> 键值对的列表。 这就是为什么你会得到["key&lt;string&gt;": value&lt;Array&lt;string&gt;&gt;] 的结构 抱歉,这只是我的记号。

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-27
    • 2015-08-13
    • 2012-01-25
    • 2022-01-10
    • 1970-01-01
    相关资源
    最近更新 更多