I can't serialize tuples. I create a template VS2019 .Net Core API project and replace the controller with:
[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;
}*/
}
When called, the first method will return: [{},{},{}]
and the second (when uncommented): ["one","two","three"]
Why aren't the tuples serialized? The example is easy to replroduce.
Anonymous objects serialize better than value tuples, but declaring them is more verbose:
[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;
}
}
I think this makes them clearer and more importantly it returns the expected: [{"number":1,"text":"one"},{"number":2,"text":"two"},{"number":3,"text":"three"}]
If you want to be really clear what your API methods are returning then I would declare DTO/model ojects to return.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With