Just Code‎ > ‎

F# - Couchbase - Serialize from JSON to Generic Object and from Generic object to JSON

posted Oct 2, 2012, 5:23 AM by Peter Henell   [ updated Oct 2, 2012, 5:24 AM ]
Add references to System.Runtime.Serialization and System.XML to your project.

For the Couchbase functionality you also need to download and add the Couchbase .Net Client libraries and configure your app.config to point to your Couchbase DB.

Used in this example with Couchbase to store an object as Json and then to retreive the object back again.

open Enyim
open Enyim.Caching.Memcached
open Couchbase
open System
open System.IO
open System.Runtime.Serialization.Json
open System.Text


type Customer = { First : string; Last: string; SSN: int; AccountNumber : int; }

let customerToString (cust : Customer) = 
    String.Format("First : {0}; Last: {1}; SSN: {2}; AccountNumber : {3};", cust.First, cust.Last, cust.SSN, cust.AccountNumber)

let toJson (o: 'a) = 
    let ms = new MemoryStream()
    let serialiser = new DataContractJsonSerializer(typeof<'a>)
    serialiser.WriteObject(ms, o) |> ignore
    let jsonString = Encoding.Default.GetString(ms.ToArray())
    ms.Dispose |> ignore
    jsonString

let fromJson<'a> (str : string) =
    let ms = new MemoryStream(Encoding.Default.GetBytes(str))
    let serialiser = new DataContractJsonSerializer(typeof<'a>)    
    let (obj :'a) = serialiser.ReadObject(ms) :?> 'a
    ms.Dispose()
    obj

let peter = { Customer.First = "Peter"; Last = "Henell"; SSN = 10; AccountNumber = 123123 }

let client = new CouchbaseClient()
client.Store(StoreMode.Add, "peter", toJson(peter)) |> ignore

let getBack = client.Get("peter") :?> string
let p = fromJson<Customer>(getBack)
printfn "%s" (customerToString p)

Console.ReadKey() |> ignore

Comments