Serializing F# Option types

后端 未结 2 1948
不知归路
不知归路 2021-01-17 20:44

Consider the F# fragment below:

type MyType = {  
    CrucialProperty: int
    OptionalProperty: string option 
}

let first = { CrucialProperty = 500; Optio         


        
2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-17 21:27

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

提交回复
热议问题