Search code examples
f#json.net

How Can I Deserialize Json With F#?


I am attempting to deserialize some very simple json into 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 a 0 in the count. By the way, I was originally defining meta like this:

type meta = {
   count: int
}

And I changed to using the Automatic property because I thought that Newtonsoft.Json might not be able to construct the object correctly.

I would be surprised if my version of F#/Windows makes a difference in this case but just for sake of completeness: I'm trying this with the F# 3.0 Repl (11.0.60315.1) and I'm running on a Win7 x64 (SP1) box.


Solution

  • Try removing the outer-most set of curly braces from your JSON. Right now, you have an object containing an instance of meta. That's probably throwing off JSON.NET. In other words, I got it to run fine by using:

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

    [Updated base on comments]

    Alternately, you could keep the JSON as-is, and provide a more complex type tree in F#. For example:

    type Foo =
      { meta : Meta }
    and Meta =
      { count : int }