0

in the previous asp.net framework, we can use nullvaluehandling (json.net) to ignore the null JSON value.

but now in asp.net core, it's starting using system.text.json. how can I set null value handling using this library?

thanks

dbc
  • 104,963
  • 20
  • 228
  • 340
10120
  • 95
  • 8

1 Answers1

1

In System.Text.Json 5.x:

new JsonSerializerOptions() { IgnoreNullValues = true }

It became obsolete in 6.x and now this should be used:

new JsonSerializerOptions() { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }
Maku
  • 1,464
  • 11
  • 20
  • 1
    I want to use it during deserialization. WhenWritingNull seems to only work when converting objects to JSON. i want to set default value if the json it's null or empty – 10120 Jun 30 '22 at 01:34
  • Unfortunately that is not currently supported by built-in mechanisms. Quote from https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-migrate-from-newtonsoft-how-to?pivots=dotnet-5-0#reuse-rather-than-replace-properties Reuse rather than replace properties The Newtonsoft.Json ObjectCreationHandling setting lets you specify that objects in properties should be reused rather than replaced during deserialization. System.Text.Json always replaces objects in properties. Custom converters can provide this functionality. – Maku Jul 01 '22 at 13:20