我无法序列化元组。我创建了一个模板 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/