asp.net-core - 使用 .Net Core API 进行元组序列化

标签 asp.net-core serialization .net-core

我无法序列化元组。我创建了一个模板 VS2019 .Net Core API 项目并将 Controller 替换为:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    [HttpGet]
    public List<(int number, string text)> Get()
    {
        var x = new List<(int number, string text)>
        {
            (1, "one"),
            (2, "two"),
            (3, "three")
        };
        return x;
    }

    /*[HttpGet]
    public List<string> Get()
    {
        var x = new List<string>
        {
            "one",
            "two",
            "three"
        };
        return x;
    }*/
}
调用时,第一个方法将返回:[{},{},{}]第二个(未注释时):["one","two","three"]为什么元组没有序列化?
这个例子很容易重现。

最佳答案

匿名对象比值元组序列化更好,但声明它们更冗长:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    [HttpGet]
    public IList<object> Get()
    {
        var x = new List<object>
        {
            new {number = 1, text = "one"},
            new {number = 2, text = "two"},
            new {number = 3, text = "three"}
        };
        return x;
    }
}
我认为这使它们更清晰,更重要的是它返回了预期:[{"number":1,"text":"one"},{"number":2,"text":"two"},{"number":3,"text":"three"}]如果您想真正清楚您的 API 方法返回什么,那么我会声明 DTO/模型对象要返回。

关于asp.net-core - 使用 .Net Core API 进行元组序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64676796/

相关文章:

javascript - 在 .Net 中是否有更优雅的手工制作序列化 Javascript 的方法?

c# - Asp.net Core MVC - 在应用程序关闭期间获取依赖项

c# - .net core 3.0,服务未使用 HostBuilder 注册以进行集成测试

asp.net-core - Blazor 项目中出现 "No connection could be made because the target machine actively refused it."错误

swift - 使用 jSONEncoder 的自定义结构

asp.net - 添加默认 token 提供商 : what is it and how to use those "default providers"?

c# - 将数组的数组序列化为单个 XML 元素

entity-framework - 在.NET Core 5上运行的ORM

javascript - AJAX 请求不发送 cookie (NET 5)

c# - Razor页面如何找到DisplayNameFor中的字段?