我今天注意到Newtonsoft.Json的一些奇怪的输出,我不确定它是否与F#类型的交互或C#中可能发生的事情,所以我已经标记了两者.我有一个序列化的以下记录列表:
type SplitTracker =
{
[<JsonIgnore>]
split : SplitDefinition
mutable start : duration
mutable ``end`` : duration
mutable lapCount : int
mutable duration : duration Option
}
Run Code Online (Sandbox Code Playgroud)
我序列化它,JsonConvert.SerializeObject 我得到以下奇数输出:
"splits": [
{
"start@": "0.00",
"end@": "0.00",
"lapCount@": 0,
"duration@": null,
"start": "0.00",
"end": "0.00",
"lapCount": 0,
"duration": null
},
{
"start@": "0.00",
"end@": "0.00",
"lapCount@": 0,
"duration@": null,
"start": "0.00",
"end": "0.00",
"lapCount": 0,
"duration": null
}
Run Code Online (Sandbox Code Playgroud)
任何人都知道为什么会发生这种情况?数据是正确的,带有"@"符号的字段重复是问题.
您定义记录的方式是罪魁祸首.记录字段作为属性公开 - 但您使用的是可变属性.F#会把它变成一个类,它有每个mutable的字段(名称是属性名,前缀为@),以及读出它们的属性.
Json现在将尝试序列化所有字段和所有属性 - 因此您可以获得重复.
在F#interactive中尝试一下:
type SplitTracker =
{
mutable start : float
}
let t = typeof<SplitTracker>
let fields1 = t.GetFields() // This will give you a field '@start'
let props1 = t.GetProperties() // This will give you a property 'start'
Run Code Online (Sandbox Code Playgroud)
与使用普通记录时得到的对比:
type SplitTracker2 =
{
start : float
}
let t2 = typeof<SplitTracker2>
let fields2 = t2.GetFields() // You will not see any fields
let props2 = t2.GetProperties() // There is a single property 'start'
Run Code Online (Sandbox Code Playgroud)
这应该正确序列化.除此之外,它使您的代码更加惯用.