Consider the F# fragment below:
type MyType = {
CrucialProperty: int
OptionalProperty: string option
}
let first = { CrucialProperty = 500; OptionalProperty = Some("Hello")}
let second = { CrucialProperty = 500; OptionalProperty = Some(null)}
let third = { CrucialProperty = 500; OptionalProperty = None}
I wish to do serialize this type using JSON.NET so I get the following strings respectively for the cases described above:
{"CrucialProperty":500,"OptionalProperty":"Hello"}
{"CrucialProperty":500,"OptionalProperty":null}
{"CrucialProperty":500}
Essentially, the problem boils down to being able to include/exclude a property in the serialized output based on the value of that property.
I've managed to find a few "OptionConverters" out there (e.g here), but they don't quite seem to do what I'm looking for.
I would recommend FifteenBelow's converters which work with JSON.NET but provide serialization F# types https://github.com/15below/FifteenBelow.Json (apparently moved to https://github.com/kolektiv/FifteenBelow.Json).
From their usage section:
let converters =
[ OptionConverter () :> JsonConverter
TupleConverter () :> JsonConverter
ListConverter () :> JsonConverter
MapConverter () :> JsonConverter
BoxedMapConverter () :> JsonConverter
UnionConverter () :> JsonConverter ] |> List.toArray :> IList<JsonConverter>
let settings =
JsonSerializerSettings (
ContractResolver = CamelCasePropertyNamesContractResolver (),
Converters = converters,
Formatting = Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore)
Specifically what you're looking for is the the NullValueHandling = NullValueHandling.Ignore
bit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With