我正在尝试序列化“矢量”(Microsoft.FSharp.Math) 类型。我得到了那个错误:
Exception Details: System.Runtime.Serialization.SerializationException: Type 'Microsoft.FSharp.Math.Instances+FloatNumerics@115' with data contract name 'Instances.FloatNumerics_x0040_115:http://schemas.datacontract.org/2004/07/Microsoft.FSharp.Math' is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.
我尝试添加 KnownType 属性和其他一些东西,但没有任何帮助!
有人知道答案吗? 这是我使用的代码:
// [< KnownType( typeof<vector> ) >]
type MyType = vector
let public writeTest =
let aaa = vector [1.1;2.2]
let serializer = new DataContractJsonSerializer( typeof<MyType> )
let writer = new StreamWriter( @"c:\test.txt" )
serializer.WriteObject(writer.BaseStream, aaa)
writer.Close()
最佳答案
我认为 F# vector
类型没有为 JSON 序列化提供所有必要的支持(并且在内部是一个相当复杂的类型)。在您的情况下,最好的办法可能是将其转换为数组并序列化该数组(这也肯定会生成更短、更高效的 JSON)。
转换非常简单:
let aaa = vector [1.1;2.2]
let arr = Array.ofSeq aaa // Convert vector to array
// BTW: The 'use' keyword behaves like 'using' in C#
use writer = new StreamWriter( @"c:\test.txt" )
let serializer = new DataContractJsonSerializer()
serializer.WriteObject(writer.BaseStream, aaa)
要将数组转换回向量,您可以使用 Vector.ofSeq
(与上面示例中使用的 Array.ofSeq
对应)。
关于json - 如何在 F# 中对数学向量类型进行 JSON 序列化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2877904/