1

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

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

"{"account_type":"type1","address":"US","preferred_languages":["en","ar","cn"],"displayName":"John","last_name":"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

4

1 回答 1

3

您将需要使用某种外部库。如果您想充分利用 F#,可以使用F# Data JSON 类型提供程序很好地解决这个问题。

类型提供者可以从样本中推断 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
于 2018-03-08T18:12:44.260 回答