Home > other >  How to Return a struct as json with .NetCore
How to Return a struct as json with .NetCore

Time:10-13

I'm moving a .Net Framework WebAPI to .Net Core. With Framework (notably using Newtonsoft.Json), a class or a struct is returned as xml or json according to the Accept header.

With .Net Core, structs are always coming back as empty json: e.g. [{},{}].

Starting from a pared down new project (i.e. WeatherController), how do I get this to properly serialize and return non-empty json?

public struct MyStructure
{
    public double A;
    public double B;
}
    
[ApiController]
[Route("[controller]")]
public class MyStructureController : ControllerBase
{
    [HttpGet]
    public IEnumerable<MyStructure> Get()
    {
        return new List<MyStructure>
        {
            new MyStructure(){A = 1.2d, B = 5.6d},
            new MyStructure(){A = 2.2d, B = 3.3d},
        };
    }
}
//desired response:  [{"X":1.2,"Y":5.6},{"X":2.2,"Y":3.3}]

I'm not finding what I need in the supported, nor the unsupported, serialization documentation but I'm clearly overlooking something!

CodePudding user response:

Try to do public properties instead of public variables. I think system.text.json only serializes public properties by default

CodePudding user response:

You'll need to set IncludeFields = true in your JsonSerializerOptions - same for class fields). Or see the answer below (re: propeties)

CodePudding user response:

Instead of having instance variables try to change them to properties with getter and setter methods.

public struct MyStructure
{
    public double A {get;set;}
    public double B {get;set;}
}

This will help you get the desired response

 [{"X":1.2,"Y":5.6},{"X":2.2,"Y":3.3}]
  • Related