Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ASP.NET Core 6 Web API – serializing public fields

I have the requirement that my web controller needs to return a class with only public fields.
E.g. I have

public class RunningScenario
{
    public int Id;
    public string Name;
}

and want to return this from my controller like this

[ApiController]
[Route("api/[controller]")]
public class ScenarioController : ControllerBase
{
    [HttpPost("start")]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public async Task<ActionResult<RunningScenario>> StartScenario(int scenarioId)
    {
        // Error handling

        var runningScenario = await _scenariorRunner.Start(scenarioId);
        return Ok(runningScenario);
    }
}

Though, running this just returns {} instead of {"Id": 1, "Name": "Scenario 1"}.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I also tried to add the [JsonInclude] attribute to the fields, with no effect. The result is still an empty object.

So, my question is, how do I get the public fields to be serialized and deserialized?

>Solution :

Newer versions of aspnet use the json serializer from System.Text.Json by default instead of Newtonsoft.Json. By default the serializer of System.Text.Json will not serialize fields, unlike Newtonsoft.Json.

The better option is to make the fields properties (e.g. public string Name { get; set; }). If that’s really not an option you can adjust the settings of the serializer in your startup. E.g.

builder.Services.AddControllers().AddJsonOptions(o =>
{
    o.JsonSerializerOptions.IncludeFields = true;
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading