[英]Static member assignment and JSON parsing in F#
Is JSON parsing possible into a type data or any other form where I can access each individual item within F# using built-in Microsoft provided library? JSON解析是否可以转换为类型数据或任何其他形式,我可以使用内置的Microsoft提供的库访问F#中的每个单独项目?
Following is an output generated by the following code. 以下是由以下代码生成的输出。
"{"account_type":"type1","address":"US","preferred_languages":["en","ar","cn"],"displayName":"John","last_name":"Doe"}"
“{” ACCOUNT_TYPE “:” TYPE1" , “地址”: “美国”, “preferred_languages”: “恩”, “AR”, “CN”], “显示名”: “约翰”, “姓氏”:“李四“}”
type Token = {access_token: string; refresh_token: string}
type Authentication =
new() = {}
static member token = null;
member this.RequestToken(credentials) =
let url = "example.com"
let request = WebRequest.Create(url) :?> HttpWebRequest
request.Method <- "POST"
request.ContentLength <- (int64)data.Length
use requestStream = request.GetRequestStream()
requestStream.Write(data, 0, (data.Length))
requestStream.Flush()
requestStream.Close()
let response = request.GetResponse() :?> HttpWebResponse
use reader = new StreamReader(response.GetResponseStream())
let output = reader.ReadToEnd()
reader.Close()
response.Close()
request.Abort()
Authentication.token = JsonConvert.DeserializeObject<Token>(output)
// the value or constructor "Token" is not defined
Preferably in a type, for instance 例如,优选地为一种类型
type Token = {access_token: string; refresh_token: string}
Edit 编辑
Attempting using JSON.net 尝试使用JSON.net
You will need to use an external library of some kind. 您将需要使用某种外部库。 If you want to get the most out of F#, you can solve this very nicely using the F# Data JSON type provider .
如果您想充分利用F#,可以使用F#Data JSON类型提供程序很好地解决这个问题。
The type provider can infer type of JSON data from a sample, so you could parse the above data by using your sample response to guide the inference and then use the inferred type to parse more data: 类型提供程序可以从样本中推断出JSON数据的类型,因此您可以使用样本响应来解析上述数据以指导推理,然后使用推断类型来解析更多数据:
open FSharp.Data
// Define a type using a sample JSON
type Account = JsonProvider<"""
{ "account_type":"type1","address":"US",
"preferred_languages":["en","ar","cn"],
"displayName":"John","last_name":"Doe"}""">
// Now, parse actual data you loaded from somewhere
let parsed = Account.Parse(data)
// Access all the members using a member generated by the type provider.
parsed.AccountType
parsed.Address
parsed.PreferredLanguages |> Seq.length
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.