I am not getting the expected result from this F# code. I would expect t to contain values as a result of the call to JsonSchema.Parse(json) but instead it is empty. What am I doing wrong?
open Newtonsoft.Json
open Newtonsoft.Json.Schema
let json = """{
"Name": "Bad Boys",
"ReleaseDate": "1995-4-7T00:00:00",
"Genres": [
"Action",
"Comedy"
]
}"""
[<EntryPoint>]
let main argv =
let t = JsonSchema.Parse(json)
0 // return an integer exit code
As John Palmer points out, JsonSchema.Parse
parses a JSON schema, but from your question, it looks as though you want to parse a normal JSON value. This is possible with JsonConvert.DeserializeObject
:
let t = JsonConvert.DeserializeObject json
However, the signature of DeserializeObject
is to return obj
, so that doesn't particularly help you access the values. In order to do so, you must cast the return value to JObject
:
let t = (JsonConvert.DeserializeObject json) :?> Newtonsoft.Json.Linq.JObject
let name = t.Value<string> "Name"
Json.NET is designed to take advantage of C#'s dynamic
keyword, but the exact equivalent of that isn't built into F#. However, you can get a similar syntax via FSharp.Dynamic:
open EkonBenefits.FSharp.Dynamic
let t = JsonConvert.DeserializeObject json
let name = t?Name
Notice the ?
before Name
. Keep in mind that JSON is case-sensitive.
Now, name
still isn't a string, but rather a JValue
object, but you can get the string value by calling ToString()
on it, but you can also use JValue
's Value
property, which can be handy if the value is a number instead of a string:
let jsonWithNumber = """{ "number" : 42 }"""
let t = JsonConvert.DeserializeObject jsonWithNumber
let actual = t?number?Value
Assert.Equal(42L, actual)
I recommend to use Json type provider instead.
来源:https://stackoverflow.com/questions/22446909/unexpected-result-from-call-to-newtonsoft-json-from-f