How to JSON serialize math vector type in F#? How to JSON serialize math vector type in F#? json json

How to JSON serialize math vector type in F#?


I think that F# vector type doesn't provide all the necessary support for JSON serialization (and is quite a complex type internally). Perhaps the best thing to do in your case would be to convert it to an array and serialize the array (which will also definitely generate shorter and more efficient JSON).

The conversion is quite straightforward:

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) 

To convert the array back to vector, you can use Vector.ofSeq (which is a counterpart to Array.ofSeq used in the example above).


You can also use:

let v = vector [1.;3.];let vArr = v.InternalValues

to get the internal array of the vector. In this way, you don't need to create a temporary array.

Types, RowVector, Matrix also has this method to get the internal arrays.