我正在使用f#类型,并在WPF窗口的数据源上使用它并从中产生JSON:
type Customer = {
mutable Name: string ;
mutable Phone: PhoneNumber list
}
and
PhoneNumber = {
mutable Number: string
}
,但输出是:
{"Name@":"Superhero","Phones@":[{"Number@":"111","Number":"111"},{"Number@":"222","Number":"222"},{"Number@":"333","Number":"333"}],"Name":"Superhero","Phones":[{"Number@":"111","Number":"111"},{"Number@":"222","Number":"222"},{"Number@":"333","Number":"333"}]}
如果将类型更改为:
type Customer = { Name: string ; Telephone: string }
它输出我期望的JSON:
{"Name":"Superhero","Phones":[{"Number":"111"},{"Number":"222"},{"Number":"333"}]}
但是WPF绑定抛出以下例外:
twoway或OnewayTosource绑定无法在只读属性上使用
这是我用来生成JSON C#的代码:
var phonelist = new List<PhoneNumber> { new PhoneNumber("111"),
new PhoneNumber("222"),
new PhoneNumber("333")
};
var fsharpList = Microsoft.FSharp.Collections.ListModule.OfSeq(phonelist); // TODO: Use a Extension Method
var c = new EntidadesFS.DO.Customer(name: "Superhero", phones: fsharpList);
var json = Newtonsoft.Json.JsonConvert.SerializeObject(c);
为什么会发生这种情况?
如何仅使用 Mutable 输出属性名称,而无需 @ @
或如何解决这个问题?
基于对此问题的宝贵评论,还有更多搜索
我能够找到一个解决方案:
[<CLIMutable>]
[<JsonObject(MemberSerialization = MemberSerialization.OptIn)>]
type Customer = {
[<JsonProperty>] mutable Name: string
[<JsonProperty>] mutable Phones: PhoneNumber list
}
and [<CLIMutable>]
[<JsonObject(MemberSerialization = MemberSerialization.OptIn)>]
PhoneNumber = {
[<JsonProperty>] mutable Number: string
}
或更好的是,如果我将字段保持不变(f#默认),
我只需要添加 [&lt; gt;] 属性:
[<CLIMutable>]
type Customer = {
Name: string
Phones: PhoneNumber list
}
and
[<CLIMutable>]
PhoneNumber = {
Number: string
}
输出:
{"Name":"Superhero","Phones":[{"Number":"111"},{"Number":"222"},{"Number":"333"}]}
现在,这将生成 JSON ,并且也可以很好地与 WPF binding一起工作。