Skip to content

Instantly share code, notes, and snippets.

@Thorium
Created March 4, 2012 10:36
Show Gist options
  • Save Thorium/1972225 to your computer and use it in GitHub Desktop.
Save Thorium/1972225 to your computer and use it in GitHub Desktop.
Convert an object to json, and json to object
#r "System.Runtime.Serialization" // for interactive
// Reference to assembly System.Runtime.Serialization and System.Xml
open System.IO
open System.Runtime.Serialization.Json
open System.Xml
open System.Text
/// Object to Json
let internal json<'t> (myObj:'t) =
use ms = new MemoryStream()
(new DataContractJsonSerializer(typeof<'t>)).WriteObject(ms, myObj)
Encoding.Default.GetString(ms.ToArray())
/// Object from Json
let internal unjson<'t> (jsonString:string) : 't =
use ms = new MemoryStream(ASCIIEncoding.Default.GetBytes(jsonString))
let obj = (new DataContractJsonSerializer(typeof<'t>)).ReadObject(ms)
obj :?> 't
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment