序列化F#选项类型 [英] Serializing F# Option types

查看:97
本文介绍了序列化F#选项类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的F#片段:

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}

我希望使用JSON.NET序列化此类型,因此对于上述情况,我分别获得以下字符串:

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.

我设法找到了一些"OptionConverters"(例如此处),但他们似乎并没有完全按照我的要求做.

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.

推荐答案

我建议FifteenBelow的转换器与JSON.NET一起使用,但提供序列化F#类型

I would recommend FifteenBelow's converters which work with JSON.NET but provide serialization F# types https://github.com/15below/FifteenBelow.Json

在使用情况"部分

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)

具体来说,您要查找的是NullValueHandling = NullValueHandling.Ignore位.

Specifically what you're looking for is the the NullValueHandling = NullValueHandling.Ignore bit.

这篇关于序列化F#选项类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆