gpt4 book ai didi

c# - 使命名元组的名称出现在序列化的 JSON 响应中

转载 作者:可可西里 更新时间:2023-11-01 08:48:10 26 4
gpt4 key购买 nike

情况:我有多个传递对象结构的 Web 服务 API 调用。目前,我声明显式类型以将这些对象结构绑定(bind)在一起。为了简单起见,这里有一个例子:

[HttpGet]
[ProducesResponseType(typeof(MyType), 200)]
public MyType TestOriginal()
{
return new MyType { Speed: 5.0, Distance: 4 };
}

改进:我有很多这些自定义类,例如 MyType,我很想改用通用容器。我遇到了命名元组,并且可以像这样在我的 Controller 方法中成功使用它们:

[HttpGet]
[ProducesResponseType(typeof((double speed, int distance)), 200)]
public (double speed, int distance) Test()
{
return (speed: 5.0, distance: 4);
}

问题 我面临的是已解析的类型基于底层 Tuple,其中包含这些无意义的属性 Item1Item2 等示例:

enter image description here

问题:有没有人找到将命名元组的名称序列化到我的 JSON 响应中的解决方案?或者,有没有人找到一个通用解决方案,允许为可以使用的随机结构提供一个类/表示,以便 JSON 响应明确命名它包含的内容。

最佳答案

在您的案例中使用命名元组的问题在于它们只是语法糖

如果你勾选named-and-unnamed-tuples documentation你会发现部分:

These synonyms are handled by the compiler and the language so that you can use named tuples effectively. IDEs and editors can read these semantic names using the Roslyn APIs. You can reference the elements of a named tuple by those semantic names anywhere in the same assembly. The compiler replaces the names you've defined with Item* equivalents when generating the compiled output. The compiled Microsoft Intermediate Language (MSIL) does not include the names you've given these elements.

所以你在运行时而不是编译期间进行序列化时遇到问题,并且你想使用在编译期间丢失的信息。可以设计自定义序列化程序,它在编译之前使用一些代码进行初始化以记住命名的元组名称,但我想对于这个示例来说这样的复杂性太多了。

关于c# - 使命名元组的名称出现在序列化的 JSON 响应中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45932003/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com