Unexpected result from call to Newtonsoft.Json from F#

浪子不回头ぞ 提交于 2019-12-06 10:15:01
Mark Seemann

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!