Created
March 4, 2012 10:36
-
-
Save Thorium/1972225 to your computer and use it in GitHub Desktop.
Convert an object to json, and json to object
This file contains 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
#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