Is there a way in Json.NET serialization to distinguish between “null because not present” and “null because null”?

后端 未结 5 895
日久生厌
日久生厌 2020-12-01 10:51

I\'m working in an ASP.NET webapi codebase where we rely heavily on the automatic support for JSON deserialization of message bodies into .NET objects via JSON.NET.

5条回答
  •  Happy的楠姐
    2020-12-01 11:27

    You could add some metadata to your JSON objects and (most likely) DTOs. It would require additional processing, but is pretty transparent and unambiguously accomplishes what you need (assuming you can name the new field such that you know it won't collide with actual data).

    {
      "deletedItems": null,
      "field1": "my field 1",
      "nested": {
        "deletedItems": null,
        "nested1": "something",
        "nested2": "else"
      }
    }
    {
      "deletedItems": "nested",
      "field1": "new value",
      "nested": null
    }
    

    Alternatively, you could add an "isDeleted" property per field if your object model accommodates that better, but that sounds like a lot more work than a list of deleted fields.

提交回复
热议问题