问题
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.
回答1:
I would recommend FifteenBelow's converters which work with JSON.NET but provide serialization F# types https://github.com/15below/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.
回答2:
The FSharp.JsonSkippable library allows you to control in a simple and strongly typed manner whether to include a given property when serializing (and determine whether a property was included when deserializing), and moreover, to control/determine exclusion separately of nullability. (Full disclosure: I'm the author of the library.)
来源:https://stackoverflow.com/questions/29675087/serializing-f-option-types