Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing F# Option types

Tags:

json.net

f#

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.

like image 655
Lawrence Avatar asked Apr 16 '15 12:04

Lawrence


1 Answers

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.

like image 102
Reid Evans Avatar answered Oct 04 '22 01:10

Reid Evans