如何使用 WebAPI 返回 Dictionary<complexType,int>

ff8*_*nia 7 c# xml json asp.net-web-api

我提供了一个以这种方式完成的 WebApi 2 端点:

我的控制器很简单:

 public IDictionary<MyClass, int> GetMyClasses(string id)
 {
    Dictionary<MyClasses, int> sample = new Dictionary<MyClasses, int>();

    sample.Add(new MyClasses()
    {
       Property1 = "aaa",
       Property2 = 5,
       Property3 = 8
    },10);

    return sample;
 }
Run Code Online (Sandbox Code Playgroud)

MyClass 的结构是:

public class MyClass
{
   string Property1 {get;set;}
   int Property2 {get;set;}
   int Property3 {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

当我运行我的网络服务时,帮助程序网页显示预期的输出是:

{ "MyNamespace.MyProject.MyClass": 1 }
Run Code Online (Sandbox Code Playgroud)

另一方面,xml 示例是我想要的(除了我想要 json,而不是 xml):

<ArrayOfKeyValueOfMyClassintl85fHlC_P xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
  <KeyValueOfMyClassintl85fHlC_P>
    <Key xmlns:d3p1="http://schemas.datacontract.org/2004/07/MyNamespace.MyProject.MyClass">
      <d3p1:Property1>sample string 4</d3p1:Property1>
      <d3p1:Property2>8</d3p1:Property2>
      <d3p1:Property3>5</d3p1:Property3>
    </Key>
    <Value>1</Value>
  </KeyValueOfMyClassintl85fHlC_P>
</ArrayOfKeyValueOfMyClassintl85fHlC_P >
Run Code Online (Sandbox Code Playgroud)

我还使用 Postman 运行了端点,它确认返回的值是 WebApi 开箱即用页面预览的值。

为什么 json 是“错误的”,而 xml 做得很好(我的意思是包含所有数据)?

更新:

我希望 MyClass 像这样在 json 中序列化:

{
  "Property1": "sample string 4",
  "Property2": 8,
  "Property3": 5
}
Run Code Online (Sandbox Code Playgroud)

这应该是我的字典键的结构,因为它在 xml 表示中。

谢谢

cod*_*key 6

这有点 hacky,但我通过在通过 JsonConvert 运行它之前将 Dictionary 转换为 List 对象取得了成功。一探究竟:

IDictionary<MyClass,int> dict = new Dictionary<MyClass, int>();
MyClass classy = new MyClass() { value = value };
dict.Add(classy, 5);
string json = JsonConvert.SerializeObject(dict); //<--- Returns [{MyClass: 5}], boo
Run Code Online (Sandbox Code Playgroud)

然而 。. .

string json = JsonConvert.SerializeObject(dict.ToList()); //<--- Returns [{Key: blah blah blah, Value: 5}], nice
Run Code Online (Sandbox Code Playgroud)

希望有帮助。


Rya*_*ann 4

您的控制器是什么样的?端点应该看起来像这样:

[Route("")] 
public IHttpActionResult Get() 
{ 
    IDictionary<MyClass, int> resource = new Dictionary<MyClass, int> 
    {
        { new MyClass {Property1="1", Property2=2, Property3=3}, 0 },
        { new MyClass {Property1="11", Property2=22, Property3=33}, 1 },
    };

    return Ok(resource); 
} 
Run Code Online (Sandbox Code Playgroud)

如果此后您仍然遇到 JSON 序列化问题,您可以JsonFormatter在 Web API 中配置默认​​类型:GlobalConfiguration.Configuration.Formatters.JsonFormatter;。有关详细信息,请参阅ASP.NET Web API 序列化文档。