1

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)

cateyes
  • 5,208
  • 2
  • 24
  • 31
  • I haven't debugged it, but your issue sounds similar (though not identical) to [Why are all the collections in my POCO are null when deserializing some valid json with the .NET Newtonsoft.Json component](https://stackoverflow.com/q/32491966). – dbc Jul 24 '17 at 10:55
  • Also see [this answer](https://stackoverflow.com/a/45331960/10263) for an explanation of what is going on and how to fix it. The question is a little different, but your code follows the same pattern and has the same problem and possible solutions. – Brian Rogers Aug 06 '17 at 08:53

0 Answers0