F#中的静态成员赋值和JSON解析

时间:2018-03-08 17:38:07

标签: json f# jsonparser

JSON解析是否可以转换为类型数据或任何其他形式,我可以使用内置的Microsoft提供的库访问F#中的每个单独的项目?

以下是由以下代码生成的输出。

  

“{” ACCOUNT_TYPE “:” TYPE1" , “地址”: “美国”, “preferred_languages”:[ “EN”, “AR”, “CN”], “显示名”: “约翰”, “姓氏” : “Doe的”}“

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

最好是一种类型,例如

type Token = {access_token: string; refresh_token: string}

修改

尝试使用JSON.net

1 个答案:

答案 0 :(得分:3)

您需要使用某种外部库。如果你想充分利用F#,你可以使用F# Data JSON type provider很好地解决这个问题。

类型提供程序可以从样本中推断出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