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: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
30: 
31: 
32: 
33: 
34: 
35: 
36: 
37: 
38: 
39: 
40: 
 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
#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
namespace System
namespace System.IO
namespace System.Runtime
namespace System.Runtime.Serialization
namespace System.Runtime.Serialization.Json
namespace System.Xml
namespace System.Text
val typeof<'T> : System.Type
Multiple items
val string : value:'T -> string

--------------------
type string = System.String
type obj = System.Object

More information

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