从F#调用Newtonsoft.Json的意外结果 [英] Unexpected result from call to Newtonsoft.Json from F#

查看:62
本文介绍了从F#调用Newtonsoft.Json的意外结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有从此F#代码中获得预期的结果.我希望t包含作为对JsonSchema.Parse(json)的调用的结果,但它为空.我在做什么错了?

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

推荐答案

正如John Palmer指出的那样,JsonSchema.Parse解析JSON schema ,但是从您的问题来看,好像您想解析普通的JSON .使用JsonConvert.DeserializeObject:

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

但是,DeserializeObject的签名将返回obj,因此这对访问值没有特别帮助.为此,必须将返回值强制转换为JObject:

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旨在利用C#的dynamic关键字,但F#并未内置该关键字的完全等效项.但是,您可以通过 FSharp.Dynamic

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

Name之前注意?.请记住,JSON区分大小写.

Notice the ? before Name. Keep in mind that JSON is case-sensitive.

现在,name仍然不是字符串,而是一个JValue对象,但是您可以通过在其上调用ToString()来获取字符串值,但是您也可以使用JValueValue属性,如果该值是数字而不是字符串,则可以很方便:

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)

这篇关于从F#调用Newtonsoft.Json的意外结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆