从ASP.NET Core Web API返回JSON关联数组的问题 [英] Issue returning a JSON associative array from an ASP.NET Core Web API

查看:191
本文介绍了从ASP.NET Core Web API返回JSON关联数组的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ASP.NET Core 3.1中有一个Web API方法,该方法返回一个可枚举的对象列表:

I have a Web API method in ASP.NET Core 3.1 that returns an enumerable list of objects:

public async Task<IEnumerable<MyObject>> Get()

默认情况下,Web API返回JSON.这一直很好,直到我添加了Dictionary< int,object>类型的属性.到MyObject,无法意识到ASP.NET Core 3.1用来构建响应的任何序列化程序都无法序列化Dictionary(错误是"type Dictionary

The Web API returns JSON by default. This has worked fine, until I added a property of type Dictionary<int, object> to MyObject, not realizing that whatever serializer ASP.NET Core 3.1 is using to build the response can't serialize a Dictionary (error is "type Dictionary<int, object> is not supported"). I can reproduce the same error by trying to serialize the Dictionary using the new System.Text.Json library, which is what I'm guessing is being used by the web API to build the JSON response.

由于JsonConvert仍然可以很好地序列化Dictionary,因此在该方法中手动进行序列化并不困难.但这意味着做出我自己的JSON响应,并将其作为内容字符串返回,这似乎……不好.

Since JsonConvert still serializes Dictionary just fine, it wouldn't be hard to do the serialization manually in the method. But that means making my own JSON response and returning it as a content string, which just seems ... not great.

我还可以使用Web API可以正确序列化为JSON的另一种关联数组类型吗?还是有一种方法可以配置Web API以使用可以处理Dictionary的JSON序列化库?还是我只是为此方法制作自己的JSON响应?

Is there another associative array type I could be using that the web API can serialize into JSON correctly? Or is there a way to configure the web API to use a JSON serialization library that can handle Dictionary? Or am I just stuck making my own JSON response for this method?

要清楚一点,我很好奇这是可能的,每种都有什么优点或缺点,以便我可以根据自己的情况选择一个好的解决方案.

To be clear, I am curious which of these are possible, what the advantages or disadvantages are to each, so that I might choose a good solution for my circumstance.

推荐答案

此答案来自@dbc.我没有意识到System.Text.Json很难对Dictionary进行序列化,而通常与Dictionary无关,而对于使用非字符串键的Dicitonary来说尤其如此.对于我们来说,编写一个转换器以将必要的Dictionary转换为字符串类型是很简单的,然后内置的JSON序列化就可以很好地处理它.

This answer comes from @dbc in the comments. I hadn't realized that the System.Text.Json difficulty with serializing Dictionary wasn't with Dictionary generally, but specifically with Dicitonary using a non-string key. It was trivial for us to write a converter to translate the necessary Dictionary to a string-keyed type, and then the built-in JSON serialization handled it just fine.

谢谢@dbc!

这篇关于从ASP.NET Core Web API返回JSON关联数组的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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