使用.Net Core API进行元组序列化



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

[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/model ojects。

我认为大多数序列化库都使用公共属性来生成输出,而C#7元组则使用公共字段。我们可以通过反思来检查这一点。您可以看到,如果只返回带有公共字段的类的对象,json响应将具有相同的输出。如果它不符合您的期望,您可以使用不同的序列化策略。提供了一些方便的答案

using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
[HttpGet]
public object Get()
{
var x = (1, 1);
var properties = x.GetType().GetProperties(); // count == 0
var fields = x.GetType().GetFields(); // count == 2
return x;
}
[HttpGet("obj")]
public object GetMyObj()
{
return new MyObj();
}
public class MyObj
{
public int i = 1;
}
}
}

您可以返回OK响应:

[HttpGet]
public IHttpActionResult Get()
{
var x = new List<(int number, string text)>
{
(1, "one"),
(2, "two"),
(3, "three")
};
return Ok(x);
}

您需要使用Newtonsoft.Json进行序列化。从Nuget:安装软件包

Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson -Version 3.1.9

并使用以下代码将其序列化:

var y = JsonConvert.SerializeObject(x);

最新更新