Last active
August 29, 2015 14:20
-
-
Save SteveGilham/73cc1301d00fee013030 to your computer and use it in GitHub Desktop.
Sample of serializing union type
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
open System.IO | |
open System.Runtime.Serialization.Json | |
open System.Text | |
let exprTypes = GetUnionTypes baseType | |
let ToJson<'t> (myObj:'t) = | |
use ms = new MemoryStream() | |
DataContractJsonSerializer(typeof<'t>, exprTypes).WriteObject(ms, myObj) | |
Encoding.Default.GetString(ms.ToArray()) | |
let FromJson<'t> (jsonString:string) : 't = | |
use ms = new MemoryStream(Encoding.Default.GetBytes(jsonString)) | |
let obj = DataContractJsonSerializer(typeof<'t>, exprTypes).ReadObject(ms) | |
obj :?> 't | |
let value = Num 3 | |
let json = ToJson value | |
let recovered : expr = FromJson json | |
;; | |
val exprTypes : seq<Type> | |
val ToJson : myObj:'t -> string | |
val FromJson : jsonString:string -> 't | |
val value : expr = Num 3 | |
val json : string = "{"__type":"FSI_0002.expr.Num:#","item":3}" | |
val recovered : expr = Num 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment