Serializing F# Option types

后端 未结 2 1947
不知归路
不知归路 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:17

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

    0 讨论(0)
  • 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<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.

    0 讨论(0)
提交回复
热议问题