I'm working with .NET 5 and Api Controllers. In my startup class (ConfigureServices) I have the following:
services.AddControllers().AddNewtonsoftJson(x =>
{
x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
Then I have a controller like this:
[HttpPost]
public async Task<ActionResult<Company>> PostCompany(Company company)
{
}
And Company is a class like this
public class Company : Entity
{
Coordinates coordinates;
public int CompanyId { get; set; }
public string Name { get; set; }
public NpgsqlTypes.NpgsqlBox Bounds { get; set; }
[NotMapped]
public Coordinates Coordinates
{
get { return coordinates ?? new Coordinates(); }
set { coordinates = value; Bounds = new NpgsqlTypes.NpgsqlBox(coordinates.Top, coordinates.Right, coordinates.Bottom, coordinates.Left); }
}
}
public class Coordinates
{
public double Left { get; set; }
public double Right { get; set; }
public double Bottom { get; set; }
public double Top { get; set; }
}
From postman I send a POST with this body (Content-Type: application/json in the Headers)
{
"companyId":0,
"name":"company 1",
"coordinates":{
"left":2,
"right":5,
"bottom":43,
"top":3
}
}
name has the correct value but why coordinates in the parameter of the api controller is always 0 in all its values? Seems it's newtonsoft deserialization because if I use this
public async Task<ActionResult<Company>> PostCompany(Object company2)
{
var jsonString = company2.ToString();
Company company = JsonConvert.DeserializeObject<Company>(jsonString);
}
I see the coordinates values in the company2 but not when deserialized into company object (which has 0 for all the coordinates).
Any idea? Thanks in advance. Guillermo.
[NotMapped]it's probably what's causing itCoordinatesyou need to doreturn coordinates ?? coordinates = new Coordinates();because Json.NET never sets the value back after it is populated. For why see this answer to Why are all the collections in my POCO are null when deserializing some valid json with the .NET Newtonsoft.Json component which is basically the same problem, although it asks about JSON arrays rather than objects.[JsonProperty(ObjectCreationHandling = ObjectCreationHandling.Replace)]topublic Coordinates Coordinateswhich will forceCoordinatesto be freshly allocated and set back during serialization. See How to apply ObjectCreationHandling.Replace to selected properties when deserializing JSON? for a similar question.