Returning a Vector3 over an ASP.NET Core Web API returns empty JSON

Jacob Clinton 26 Reputation points
2022-06-21T14:46:41.687+00:00

I'm assuming I'm doing something wrong here but whenever I try to return a Vector2/Vector3 over an ASP API it always gives me '{}'. JsonConvert seems to be able to serialize and deserialize it just fine but not over an API.

To replicate this create a new 'ASP.NET Core Web API' project and replace the WeatherController Get method with:

[HttpGet(Name = "GetWeatherForecast")]  
public Vector3 Get()  
{  
    return Vector3.One;  
 }  

Now calling it will return an empty JSON object ('{}').

213477-apivector3.png

Any help with this would be greatly appreciated.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,199 questions
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 56,846 Reputation points
    2022-06-21T15:58:29.653+00:00

    the issue is fields are not serialized by default. you need to configure:

    builder.Services.AddControllers().AddJsonOptions(o => o.JsonSerializerOptions.IncludeFields = true);

    But I'd recommend not doing this. You should create a simple object to return:

    public class Vector3Model  
    {  
        public float X { get; set; }  
        public float Y { get; set; }  
        public float Z { get; set; }  
      
        public Vector3Model() {}  
        public Vector3Model(Vector3 v)  
        {  
            X = v.X;  
            Y = v.Y;  
            Z = v.Z;  
        }  
        public Vector3 ToVector3()   
        {  
          return new Vector3(X, Y, Z);  
        }  
    }  
    

    then its:

        return new Vector3Model(Vector3.One);  
      
    

    note: by default swagger also does not include fields in the schema, you will need to define the schema to use fields

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful