如何返回Dictionary< complexType,int>使用WebAPI [英] How to return Dictionary<complexType,int> with WebAPI

查看:84
本文介绍了如何返回Dictionary< complexType,int>使用WebAPI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在提供通过以下方式完成的WebApi 2端点:

I'm providing a WebApi 2 endpoint that is done in this way:

我的控制器很简单:

 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;
 }

MyClass的结构是:

The structure of MyClass is:

public class MyClass
{
   string Property1 {get;set;}
   int Property2 {get;set;}
   int Property3 {get;set;}
}

当我运行Web服务时,帮助程序页面会向我显示预期的输出为:

When I run my webservice, the helper webpage shows me that the expected outputs are:

{ "MyNamespace.MyProject.MyClass": 1 }

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

On the other hand the xml sample is what I'd like (except that I want the json, not the 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 >

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

I also ran the endpoint with Postman and it confirms that the returned value is the one previewed by the WebApi out of the box page.

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

Why the json is "wrong" and the xml is well done (I mean that contains all the data)?

已更新:

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

I expected MyClass serialized in json like this:

{
  "Property1": "sample string 4",
  "Property2": 8,
  "Property3": 5
}

这应该是我字典的键的结构,就像它在xml表示中一样.

This should be the structure of the key of my dictionary, as it is in the xml representation.

谢谢

推荐答案

这有点hacky,但是在通过JsonConvert运行Dictionary之前,通过将Dictionary转换为List对象,我获得了成功.检查一下:

This is kind of hacky, but I had success by converting the Dictionary to a List object before running it through JsonConvert. Check it out:

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

而. . .

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

希望有帮助.

这篇关于如何返回Dictionary&lt; complexType,int&gt;使用WebAPI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆