json - 如何在 F# 中对数学向量类型进行 JSON 序列化?

标签 json math serialization f#

我正在尝试序列化“矢量”(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/

相关文章:

json - 什么是grails.converters.deep.JSON的替代品

javascript - js解析json多个元素与单个元素

c# - 二次方程式

c# - Web API - 返回复杂对象列表时出错

javascript - 创建基于另一个 JSON 作为键和值的 JSON?

ios - 如何异步加载 JSON 数据并在 Objective-C 数据加载期间填充 UITableView

python - 如何将 Python 对象序列化为 XML?

java - 需要在不使用 java.util.Map 的情况下创建可序列化的键值映射,使用我的解决方法继续遇到 NullPointerException

algorithm - 模式和序列 - 将 'a' 表示为 'n' 的函数

给定 3 个点找到圆弧、圆心、半径和角度的算法