How can I deserialize Json with F #?

I am trying to deserialize very simple json in F # with Newtonsoft.Json 5.0.4:

#if INTERACTIVE #r "C:/Users/OCatenacci/fshacks/CreateWeeklySWEEventsEmail/packages/Newtonsoft.Json.5.0.4/lib/net40/Newtonsoft.Json.dll" #endif open System open Newtonsoft.Json type meta() = class member val count = 0 with get, set end let testjson = """{ "meta": { "count": 15 } }""" let o = JsonConvert.DeserializeObject<meta>(testjson) 

meta always gets 0 in the score. By the way, I initially defined the meta as:

 type meta = { count: int } 

And I switched to using the Automatic property because I thought Newtonsoft.Json might not be able to build the object correctly.

I would be surprised if my version of F # / Windows mattered in this case, but only for completeness: I try this with the F # 3.0 Repl (11.0.60315.1) and I run Win7 x64 (SP1).

+4
source share
2 answers

Try removing the outermost set of curly braces from your JSON. Right now you have an object containing a meta instance. This probably drops JSON.NET. In other words, I got it to work fine using:

 let testjson = "{ 'count' : 15 }" 

[Updated comment base]

Alternatively, you can keep JSON as-is and provide a more complex type tree in F #. For instance:

 type Foo = { meta : Meta } and Meta = { count : int } 
+5
source

With FSharp.Json, you can only use post types β€” you no longer need to define classes. The structure of the entries above is sufficient:

 type Foo = { meta : Meta } and Meta = { count : int } let testjson = """{"meta": {"count": 15}}""" open FSharp.Json let data = Json.deserialize<Foo> testjson 

Disclosure: I am the author of the FSharp.Json library.

+1
source

All Articles