I've an ASP.NET Core MVC Web API application. The controller has a POST action which accepts a simple object as shown below:
public async Task<IActionResult> Post([FromBody] SimpleObj o) {
return await base.Post(o);
}
public class SimpleObj {
private Record _record;
public Record Record { get => _record ?? new Record(); set => _record = value; }
}
public class Record {
public string Key { get; set; }
public string Value { get; set; }
}
If i send a HTTP POST request with a JSON payload:
{
"record": {
"key": "Test1",
"value": "Passed"
}
}
The received SimpleObj in the controller's POST action, I would expect it has its Record property be set to Key = "Test1"
, and Value = "Passed"
. But I found its Record property has been set to null!
If I change the code from get => _record ?? new Record();
to get => _record;
, or if I use public Record Record { get; set; } = new Record();
instead, then it works fine. I can see the Record
part in JSON has been deserialised properly into the Record property which has been set to Key = "Test1"
, and Value = "Passed"
!
But the code get => _record ?? new Record();
means when retrieving the Record back if it's null then create an default Record object which should rather affect serialisation not deserialisation, why doesn't Json.NET handle this properly in deserialisation? (I'm using Newtonsoft.Json 9.0.1)