3 people like it.

Convert an object to json, and json to object

There is a namespace System.Runtime.Serialization.Json To serialize generic object you can do like this...

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
/// 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
val internal json : myObj:'t -> obj

Full name: Script.json


 Object to Json
val myObj : 't
val ms : System.IDisposable
val typeof<'T> : System.Type

Full name: Microsoft.FSharp.Core.Operators.typeof
val internal unjson : jsonString:string -> 't

Full name: Script.unjson


 Object from Json
val jsonString : string
Multiple items
val string : value:'T -> string

Full name: Microsoft.FSharp.Core.Operators.string

--------------------
type string = System.String

Full name: Microsoft.FSharp.Core.string
Multiple items
val obj : obj

--------------------
type obj = System.Object

Full name: Microsoft.FSharp.Core.obj
Next Version Raw view Test code New version

More information

Link:http://fssnip.net/1l
Posted:3 years ago
Author:Tuomas Hietanen
Tags: json , serialization