11

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.

Lawrence
  • 3,287
  • 19
  • 32

2 Answers2

4

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.

dbc
  • 104,963
  • 20
  • 228
  • 340
Reid Evans
  • 1,611
  • 15
  • 19
0

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.)

cmeeren
  • 3,890
  • 2
  • 20
  • 50