Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tuple serialization with .Net Core API

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.

like image 696
Marko Avatar asked Nov 26 '22 22:11

Marko


1 Answers

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.

like image 142
Richard Garside Avatar answered Nov 29 '22 05:11

Richard Garside